1:case context:
?現設計一個關于鴨子的系統,一個抽象類Duck,方法為quack(),swim(),abstract display()(具體子?? 類實現)。現需求為有部分類型的鴨子可以fly(),如何實現。
?? a:繼承:把fly()提到Duck類中,可實現代碼復用。
???????????????? 問題:違反繼承原則,父類的方法必須是所有子類都具有的行為,代碼維護 時如加入一? 種新類 型木頭鴨就沒有fly()行為。
? b:接口:寫一個flyable接口,所有有fly()行為的鴨子都實現這個接口。
??????????????? 問題:不能實現代碼復用。
??
2: 重新分析:
??? fly()行為不是每個子類都有,fly()的具體實現可能會變化(有的是用翅膀飛行,有的是滑行, 或是其它沒有發現的方法,總之它是會變的(change,add))。
??? Design Principal:Identify the aspects of your application that vary and seperate them from what stays the same。
??? (take the parts that vary and encapsulate them,so that later you can alter and extend the parts that vary without affecting those don't?)
?? 解決方法:
????????? 寫FlyBehavior接口,和兩個實現類FlyWithWings和FlyNoWay,這樣把Fly的行為從duck類的內部提了出來,我們可以修改和增加行為而不影響其它代碼。
????????? 把FlyBehavior實例作為Duck的屬性,子類構造時可以通過new FlyBehavior的實現類設置此屬性,(因為FlyBehavior是接口,我們可以在Runtime 改變它),然后在Duck寫performFly()實現方法為代理flyBehavior.fly()。
??? Design Principal:Favor composition than inheirtance.
??? (1:change behavior at runtime.2:encapsulate a family of algorithms into their own classes)
?? Strategy pattern: define a family of algorithms,encapsulates each one,and make them interchangeable. Strategy lets the algorithm vary independently from the client that use it.
3:現實應用:
?? 圖書打折計算:有多種打折策略,折扣可能會變動或增加。
?? 排序系統:先寫出各種排序實現,根據情況動態選擇排序策略。?