八月的策略模式

來源:互聯網
上載者:User

標籤:style   http   color   java   使用   os   2014   ar   

一、前言

某大牛曾經這樣描述過設計模式:

設計模式其實就三個準則:一是中意於組合而不是繼承 。二是依賴於介面而不是實現。三是高內聚,低耦合。

且不忙討論這句話是否正確,但從這句話裡的口氣中我學到一個道理,我其實不應該去畏懼設計模式,以為這是多麼難的東西,當以平常心對待設計模式,並將其使用到我們的項目中。


二、原理 1、繼承

通過繼承來封裝一個個擁有共同介面的獨立的演算法


2、多態機制

通過繼承我們定義了多個演算法,而通過java的多台機制我們則可以讓這些演算法之間進行互換。


3、組合

通過組合對策略屏蔽高層模組對策略、演算法的直接存取,封裝可能存在的變化。

三、策略模式中的三種角色 

策略模式由三個角色群組成:
1) 演算法使用環境(Context)角色:它也叫做上下文角色,起承上啟下封裝作用,屏蔽高層模組對策略、演算法的直接存取,封裝可能存在的變化


2) 抽象策略(Strategy)角色:策略、演算法家族的抽象,通常為介面,定義每個策略或演算法必須具有的方法和屬性。


3) 具體策略(Concrete Strategy)角色:實現了抽象策略角色定義的介面。策略模式各個角色之間關係的類圖表示:

四、一些設計原則

1、多用組合,少用繼承

2、針對介面編程,而不是針對實現編程

3、為了互動對象之間的松耦合設計而努力

4、要依賴抽象,不要依賴具體的類

5、最少知識原則:只和你的密友交談

6、好萊塢原則:別調用(打電話給)我們,我們會調用(打電話給)你

7、一個類應該只有一個引起變化的原因

五、例子 1、抽象策略角色
package com.fengshu.limanman.dao;public interface IFlyDao {public void fly();}
2、具體策略角色
package com.fengshu.limanman.dao.impl;import com.fengshu.limanman.dao.IFlyDao;public class CanNotFlyDaoImpl implements IFlyDao {public void fly() {System.out.print("sorry i can not fly");}}
3、又一個具體策略角色
package com.fengshu.limanman.dao.impl;import com.fengshu.limanman.dao.IFlyDao;public class FlyWithWingDaoImpl implements IFlyDao {@Overridepublic void fly() {System.out.println("hello i am flying");}}


4、上下文角色
package com.fengshu.limanman.model;import com.fengshu.limanman.dao.IFlyDao;public class FlyContext {private IFlyDao iFlyDao;public FlyContext(IFlyDao iFlyDao) {this.iFlyDao = iFlyDao;}public void tryFly() {iFlyDao.fly();}}
5、測試類別
package com.fengshu.limanman.test;import org.junit.Test;import com.fengshu.limanman.dao.impl.CanNotFlyDaoImpl;import com.fengshu.limanman.dao.impl.FlyWithWingDaoImpl;import com.fengshu.limanman.model.FlyContext;public class TestFly {@Testpublic void testTryFly() {FlyContext flyContext = new FlyContext(new FlyWithWingDaoImpl());flyContext.tryFly();FlyContext flyContext2 = new FlyContext(new CanNotFlyDaoImpl());flyContext2.tryFly();}}
6、測試結果
hello i am flyingsorry i  can not fly


六、總結
七、後記

希望下次問自己什麼事策略模式的時候不要再答不上來,也就是說我不想再寫九月的策略模式了。。。。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.