Thinking in Java 4th chap9笔记-接口(四)

2014-11-24 11:10:32 · 作者: · 浏览: 3
分处理器
class Spliter extends Processor
{
//注意这里是协变返回类型
@Override
String process(Object input)
{
//注意Arrays.toString用法
return Arrays.toString(((String)input).split(" "));
}
}
//*****另一组看似具有相同接口的类 *****//
//波形
class Waveform
{
private static long counter;
private static long id = counter++;
@Override
public String toString()
{
return "Waveform " + id;
}
}
//Filter
class Filter
{
public String name()
{
return getClass().getSimpleName();
}
Waveform process(Waveform input)
{
return input;
}
}
//LowPass
class LowPass extends Filter
{
private double cutoff;
public LowPass(double cutoff)
{
this.cutoff = cutoff;
}
//这里处理没有发生变化 dummy
@Override
Waveform process(Waveform input)
{
return input;
}
}
//HighPass
class HighPass extends Filter
{
private double cutoff;
public HighPass(double cutoff)
{
this.cutoff = cutoff;
}
@Override
Waveform process(Waveform input)
{
return input;
}
}
//BandPass
class BandPass extends Filter
{
private double lowCutoff;
private double hightCutoff;
public BandPass(double lc,double hc)
{
lowCutoff = lc;
hightCutoff = hc;
}
@Override
Waveform process(Waveform input)
{
return input;
}
}
package com.book.chap9.Interface;
/**
*
*组合接口的名字冲突,请尽量避免在打算组合的不同接口中使用相同的方法名
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-5-7
*
*/
public class CombineInterfaceCollision
{
}
//void f
interface I1
{
void f();
}
//int f(int)
interface I2
{
int f(int i);
}
//int f()
interface I3
{
int f();
}
//int f()
class C
{
public int f()
{
return 1;
}
}
//实现了两个接口
class C2 implements I1,I2
{
@Override
public int f(int i)
{
return 1;
}
@Override
public void f()//重载f
{
}
}
class C3 extends C implements I2
{
@Override
public int f(int i)//重载f
{
return 1;
}
}
class C4 extends C implements I3
{
}
//下面是编译报错的
//方法名只能是因为方法只是返回值不同而已
//The return types are incompatible for the inherited methods I1.f(), C.f()
/*class C5 extends C implements I1
{
}*/
/*interface I4 extends I1,I3
{
}*/
package com.book.chap9.Interface;
/**
*
*接口与工厂
*
*工厂方法
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-5-15
*
*/
public class Factories
{
//方法参数为一个工厂服务接口
public static void serviceConsumer(ServiceFactory factory)
{
Service service = factory.getService();
service.method1();
service.method2();
}
public static void main(Stringargs)
{
//传服务工厂1
serviceConsumer(new Implementation1Factory());
//动态灵活的更改为服务工厂2
serviceConsumer(new Implementation2Factory());
}
}
//接口服务
interface Service
{
void method1