Processor 接口↓↓↓
Processor 与 Filter 有相同的行为,所以可以用适配器包装
public interface Processor {
String name();
Object process(Object input);
}
Filter 类↓↓↓
Processor 与 Filter 有相同的行为,所以可以用适配器包装
public class Filter {
public String name() {
return getClass().getSimpleName();
}
public Waveform process(Waveform input) {return input;}
}
FilterAdapter 适配器↓↓↓
适配器FilterAdapter 实现接口Processor
public class FilterAdapter implements Processor {
Filter filter;
public FilterAdapter(Filter filter) {
this.filter = filter;
}
@Override
public String name() {
return filter.name();
}
@Override
public Object process(Object input) {
return filter.process((Waveform) input);
}
}
HighPass 类↓↓↓
public class HighPass extends Filter {
double cutoff;
public HighPass(double cutoff) {this.cutoff = cutoff;}
public Waveform process(Waveform input) {
System.out.println("cutoff ----> " + cutoff);
return input;
}
}
FilterProcessor类↓↓↓
main函数在此
FilterAdapter适配器类将HighPass包装了一下
FilterAdapter是一个Processor
HighPass是一个Filter
Apply.process()接受的是Processor
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
Apply.process(new FilterAdapter(new BandPass(3.0,4.0)), w);
}
}
Apply.process
public class Apply {
public static void process(Processor p, Object s) {
System.out.println("Using Processor ----> " + p.name());
System.out.println(p.process(s));//这里打印了 Waveform
}
}