接口的使用——适配器设计模式
/////////在电子滤波器的例子中,类库是被发现而非创建的,在这些情况下,可以使用适配器设计模式,适配器(FilterAdapter)中的代码将接受你所拥有的接口(Processor),并产生你所需要的接口,用组合将基类(Filter)与接口(Processor)联系起来。
class Waveform{
private static long counter;
private final long id=counter++;
public String toString(){ return "Waveform"+id; }
}
class Filter{
public String name(){
return getClass().getName();
}
public Waveform process(Waveform input){ return input; }
}
class LowPass extends Filter{
double cutoff;
public LowPass(double cutoff){ this.cutoff=cutoff; }
public Waveform process(Waveform input){ return input; }
}
class HighPass extends Filter{
double cutoff;
public HighPass(double cutoff){ this.cutoff=cutoff; }
public Waveform process(Waveform input){ return input; }
}
class BandPass extends Filter{
double lowCutoff,highCutoff;
public BandPass(double lowCutoff,double highCutoff){ this.lowCutoff=lowCutoff; this.highCutoff=highCutoff; }
public Waveform process(Waveform input){ return input; }
}
interface Processor{
String name();
Object process(Object input);
}
class Apply{
public static void process(Processor p,Object s){
System.out.print("Using Processor\n"+p.name()+"\n");
System.out.print(p.process(s)+"\n");
}
}
//////////适配器
class FilterAdapter implements Processor{
Filter filter;/////////////用到了代理
public FilterAdapter(Filter filter){ this.filter=filter; }
public String name(){ return filter.name(); }
public Waveform process(Object input){
return filter.process((Waveform)input);
}
}
public class FilterProcessor {
public static void main(String[] args){
Waveform w=new Waveform();
Apply.process(new FilterAdapter(new LowPass(1.0)), w);
//////////////////分析这句代码:初始化最里面的对象,一步一步向外扩张调用需要的方法。
Apply.process(new FilterAdapter(new HighPass(2.0)), w);
Apply.process(new FilterAdapter(new BandPass(3.0,4.0)), w);
}
}