# Strategy Pattern ###### tags: `Design Patten` `Strategy` 設計原則 1.針對介面來設計程式,而不要針對實作來設計程式 (Program to an interface , not an implementation) 2.包含取代繼承 (Favor object containment over class inheritance) explain : 若類別方法使用繼承來達到多型則會造成組合爆炸,因此將該責任分派出去 並且讓原類別包含 描述 1. Motivation : 如果你希望封裝演算法的細節或者是使用到的資料結構 2. Intent : 定義一組演算法,封裝每一組演算法的實作,然後可以在不同的演算法實作中隨意切換 3. Applicability : 封裝演算法或行為與期使用多重條件來決定行為,還不如套用策略模式 4. Structure :  5. Participants : Context(包含且維護Strategy實體)、Strategy(演算法介面)、ConcreteStragegy*(實作演算法介面) 6. Collaborations : 通常Context建構初期選擇其中一個ConcreteStragegy*並透過建構子傳入使Context包含其且維護, Context與Strategy介面互動來執行其演算法,在執行演算法的時候Context委派呼叫了Strategy,Context需傳遞所需要的資料給Strategy亦或是自己,無論如何只要資料足夠即可 7. Consequences : 優點 1.算法可隨意切換並且演算法還具有自己的繼承架構 2. 每個演算法被封裝進單獨的類別中開發,較好理解且維護(觀注點分離:Separation of concerns) 缺點 1. 客戶端必須知道不同以算法之間的差異,才得以選擇適合的演算法 2. 物件數量的增加 每個演算法都被獨立宣告為一個類別 8. Classification : 行為類的設計模式
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up