策略設計模式

package shejimoshi;


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();
}
}


class Downcase extends Processor{
String process(Object input){
return ((String)input).toLowerCase();
}

}



class Splitter extends Processor{
String process(Object input){
return Arrays.toString(((String)input).split(" "));
}
}

public class 策略設計模式 {
public static void process(Processor p,Object s){
System.out.println("Using Process"+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);
}

}

輸出結果如下:

Using ProcessUpcase
DISAGREEMENT WITH BELIEFS IS BY DEFINITION INCORRECT
Using ProcessDowncase
disagreement with beliefs is by definition incorrect
Using ProcessSplitter
[Disagreement, with, beliefs, is, by, definition, incorrect]



Apply.process()方法可以接受任何類型的Process,並將其應用到一個Object對象上,然後打印結果。

像本例這樣,創建一個能夠根據所傳遞的參數對象的不同而具有不同的行爲的方法,

被稱爲策略設計模式。

這類方法包含所要執行的算法中固定不變的部分,而“策略”包含變化部分。

策略就是傳遞進去的參數對象,它包含要執行的代碼。

這裏,Processor對象就是一個策略,在main()中可以看到有三種不同類型的策略應用到了String類型的s對象上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章