只要有一个方法操作的是类而非接口,那么你就只能使用这个类及其子类,如果你想要将这个方法应用于不在此继承结构中的某个类,那么你就会触霉头,接口可以在很大程度上放宽这种限制,因此,我们可以编写可服用性更好的代码
//像本例这样,创建一个能够根据所传递的参数对象的不同而具有不同行为的方法,被称为策略设计
//策略就是传递进去的参数对象,它包含要执行的代码
//: interfaces/classprocessor/Apply.java package object; import java.util.*; import static net.mindview.util.Print.*; class Processor { public String name() { return getClass().getSimpleName(); } Object process(Object input) { return input; } } class Upcase extends Processor { String process(Object input) { // Covariant return return ((String)input).toUpperCase(); } } class Downcase extends Processor { String process(Object input) { return ((String)input).toLowerCase(); } } class Splitter extends Processor { String process(Object input) { // The split() argument divides a String into pieces: return Arrays.toString(((String)input).split(" "));//split()返回String[]数组 } } public class Apply { public static void process(Processor p, Object s) { print("Using Processor " + p.name()); print(p.process(s)); } public static String s = "Disagreement with beliefs is by definition incorrect"; public static void main(String[] args) { process(new Upcase(), s); process(new Downcase(), s); process(new Splitter(), s); } } /* Output: Using Processor Upcase DISAGREEMENT WITH BELIEFS IS BY DEFINITION INCORRECT Using Processor Downcase disagreement with beliefs is by definition incorrect Using Processor Splitter [Disagreement, with, beliefs, is, by, definition, incorrect] *///:~
适配器设计模式,设配器的代码将接受你所拥有的接口,并产生你所需要的接口
//: interfaces/interfaceprocessor/FilterProcessor.java package interfaces.interfaceprocessor; import interfaces.filters.*; class FilterAdapter implements Processor { Filter filter; public FilterAdapter(Filter filter) { //FilterAapter 接受你拥有的接口Filer this.filter = filter; //然后生成你需要的Processor接口的对象 } 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); } } /* Output: Using Processor LowPass Waveform 0 Using Processor HighPass Waveform 0 Using Processor BandPass Waveform 0 *///:~