1)策略模式(Strategy Pattern)中,定義演算法族(策略組),分別封裝起來,讓他們之間可以互相替換,此模式讓演算法的變化獨立於使用演算法的客戶
2)這演算法體現了幾個設計原則,第一,把變化的程式碼從不變的程式碼中分離出來;第二,針對介面程式設計而不是具體類別(定義了策略介面);第三,多用組合/聚合,少用繼承(客戶透過組合方式使用策略)
#例如:針對環境節能,提出了三種節能方式:基頻板節能,SPC節能,產品節能,不同的節能方式,對環境設備的具體處理流程不同
(1)類別圖
##(2)編碼實作1)定義一個EsPolicy抽象類,定義esPolicyHandler方法public abstract class EsPolicy { public void esPolicyHandler() { } }
public class BbEsPolicy extends EsPolicy { @Override public void esPolicyHandler() { System.out.println("===处理基带板节能策略==="); } }
public class SpcEsPolicy extends EsPolicy { @Override public void esPolicyHandler() { System.out.println("===Spc节能策略处理==="); } }
public class ProdEsPolicy extends EsPolicy { @Override public void esPolicyHandler() { System.out.println("===产品节能策略处理==="); } }
public class EsPolicyTest { public static void main(String[] args) { EsPolicy bbEsPolicy = new BbEsPolicy(); bbEsPolicy.esPolicyHandler(); SpcEsPolicy spcEsPolicy = new SpcEsPolicy(); spcEsPolicy.esPolicyHandler(); ProdEsPolicy prodPolicy = new ProdEsPolicy(); prodPolicy.esPolicyHandler(); } }
public interface EsPolicyHandler { void esPolicyHandler(); }
執行結果===處理基底帶板節能策略===
#public class BbEsPolicyHandler implements EsPolicyHandler { @Override public void esPolicyHandler() { System.out.println("===基带板节能策略处理==="); } }登入後複製
執行結果#。
===Spc節能策略處理===
===產品節能策略處理===##問題:傳統方法是透過子類別繼承父類別並複寫父類別方法來實現不同子類別的不同行為,對類別的局部改動,尤其是超類別的局部改動,會影響其它部分,會有溢出效應3.採用策略模式
(1)類別圖
#(2)編碼實作##1)定義策略接口並定義抽象方法
public class SpcEsPolicyHandler implements EsPolicyHandler { @Override public void esPolicyHandler() { System.out.println("===Spc节能策略处理==="); } }
2)BbEsPolicyHandler實作策略接口,並實作esPolicyHandler方法
public class ProdEsPolicyHandler implements EsPolicyHandler { @Override public void esPolicyHandler() { System.out.println("===产品节能策略处理==="); } }
3)SpcEsPolicyHandler實作策略接口,並實作esPolicyHandler方法
public abstract class EsPolicy { EsPolicyHandler esPolicyHandler; public void setEsPolicyHandler(EsPolicyHandler esPolicyHandler) { this.esPolicyHandler = esPolicyHandler; } public void esPolicyHandler() { if (null != esPolicyHandler) { esPolicyHandler.esPolicyHandler(); } } }
4)Prodler實作策略接口,並實作esPolicyHandler方法
實作策略接口,並實作esPolicyHandler方法public class BbEsPolicy extends EsPolicy { public BbEsPolicy() { esPolicyHandler = new BbEsPolicyHandler(); } }
public class SpcEsPolicy extends EsPolicy { public SpcEsPolicy() { esPolicyHandler = new SpcEsPolicyHandler(); } }
public class ProdEsPolicy extends EsPolicy { public ProdEsPolicy() { esPolicyHandler = new ProdEsPolicyHandler(); } }
public class EsPolicyTest { public static void main(String[] args) { BbEsPolicy bbEsPolicy = new BbEsPolicy(); bbEsPolicy.esPolicyHandler(); SpcEsPolicy spcEsPolicy = new SpcEsPolicy(); spcEsPolicy.esPolicyHandler(); ProdEsPolicy prodEsPolicy = new ProdEsPolicy(); prodEsPolicy.esPolicyHandler(); } }
#rrreee
9)測試rrreee===Spc節能策略處理===10)執行結果
===處理基頻板節能策略===
以上是Java設計模式之策略模式實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!