標籤:執行 blog font java nbsp print 代碼 code 參數
1.策略設計模式
建立一個能夠根據所傳遞的參數對象的不同而具有不同的方法,被稱為策略設計模式。這類方法包含索要執行的演算法中固定不變的部分,而“策略”包含變化的部分。策略就是傳遞進去的參數對象。在下面的程式碼範例中,Process對象就是策略。應用在了s上。
程式碼範例:
class Process { public String getName(){ return getClass().getSimpleName(); } Object process(Object input){ return input; }}class Upcase extends Process { String process(Object input){ return ((String)input).toUpperCase(); }}class Lowercase extends Process { String process(Object input){ return ((String)input).toLowerCase(); }}public class Strategy{ public static void process(Process p,Object s){ System.out.println("Using Process " + p.getName()); System.out.println(p.process(s)); } public static String s="this is strategy design model!"; public static void main(String[] args) { process(new Upcase(),s); process(new Lowercase(),s); }}輸出:Using Process UpcaseTHIS IS STRATEGY DESIGN MODEL!Using Process Lowercasethis is strategy design model!
《java編程思想》:設計模式(不定期更新)