import java.util.Arrays;
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){
//covariant return
return((String)input).toLowerCase();
}
}
class Splitter extends Processor{
String process(Object input){
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 belifs is by definition incorrect";
public static void main(String[] args){
process(new Upcase(),s);
process(new Downcase(),s);
process(new Splitter(),s);
}
}
运行结果为
Using ProcessorUpcase
DISAGREEMENT WITH BELIFS IS BY DEFINITION INCORRECT
Using ProcessorDowncase
disagreement with belifs is by definition incorrect
Using ProcessorSplitter
[Disagreement, with, belifs, is, by, definition, incorrect]
Apply类的process()方法可以接受任何类型的Processor,并将其应用到一个Object对象上。根据所传参数对象的不同从而使行为不同,创建这种方法就被称作是策略模式(Strategy Pattern)。策略就是要传递的对象,这个例子中Processor对象就是一个策略,可以看出有3个策略应用到了String类型的s对象上。