只要有一個方法操作的是類而非接口,那么你就只能使用這個類及其子類,如果你想要將這個方法應用於不在此繼承結構中的某個類,那么你就會觸霉頭,接口可以在很大程度上放寬這種限制,因此,我們可以編寫可服用性更好的代碼
//像本例這樣,創建一個能夠根據所傳遞的參數對象的不同而具有不同行為的方法,被稱為策略設計
//策略就是傳遞進去的參數對象,它包含要執行的代碼
//: 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 *///:~