本代码拷贝自《Java编程思想第四版》接口一章。
//: interfaces/classprocessor/Apply.java package interfaces; import java.util.*; 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(" ")); } } public class Apply { public static void process(Processor p, Object s) { System.out.println("Using Processor " + p.name()); System.out.println(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] *///:~
Apply.process()方法可以接受任何类型的Processor,并将其应用到一个Object对象上,像这样创建一个能够根据所传递的参数对象的不同而具有不同行为的方法,被称为策略模式。该模式中包含固定部分和变化部分,在这里,固定部分是String s, 而变化部分是不同的Processor,Processor就是一个策略,根据策略的不同,得到不同的结果。