策略模式:创建一个能根据所传递的参数对象的不同,而具有不同行为的方法。
StrategyDemo的process()方法可以接受任何类型的Processor,并将其应用到一个object对象上,然后输出。这类方法包含所要执行的算法中固定不变的部分,而策略包含变化的部分。策略就是传递进去的参数对象,它包含要执行的代码。这里Processor对象就是一个策略,在main()中可以看到有3种不同类型的策略用到了String类型的s对象上。
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){
return ((String)input).toUpperCase(); //Coveriant return
}
}
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 StrategyDemo {
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 INCORRECTUsing Processor Downcase
disagreement with beliefs is by definition incorrect
Using Processor Splitter
[Disagreement, with, beliefs, is, by, definition, incorrect]