我的Design Pattern之旅[1]:Strategy Pattern (OO)

來源:互聯網
上載者:User

Abstract

Head First Design Patterns是用strategy pattern當作第一個範例,而陳俊杉教授也是用strategy當作授課的第一個pattern,可見strategy的確適合初學者學第一個學習的pattern。

Intent

定義一整族演算法,將每一個演算法封裝起來,可互換使用,更可以在不影響外界的情況下各別抽換所引用的演算法。

其UML標記法

GoF說strategy也稱為policy,我個人喜歡稱它為plugin,因為可以動態換演算法,如同在eclipse上可以動態換plugin一樣。

原本在單一class中有一個單一method很單純,如圖Grapher class只有drawShape()這個method,只能畫方形。

但後來『需求改變』,希望Grapher也能畫三角形和圓形,而且日後還可能增加功能,如畫橢圓形,菱形...,當然可以在Grapher陸續加上drawTriangle(),drawCircle(),drawEllipse(),但如此就違反OCP,Grapher須不斷的修改,根據DP第三規則"Identify the aspects of your application that vary and separate them from what you stays the same",將『會變』的部份另外包成class,但這些class必須要和原來的class溝通,所以必須訂出『標準』彼此才能溝通,IShape就是彼此溝通的標準,Triangle,Circle,Square則必須實做IShape這個interface,這就是strategy pattern。

我們看看這個架構,若日後還有新的shape加入,Grapher,IShape,Triangle,Circle,Square皆不用修改,符合OCP的closed for modification原則,若要加入新的class,只需實做IShape即可,符合OCP的open for extension原則,所以是非常好維護的架構,事實上,.NET Framework和STL都用了很多strategy pattern。

簡言之,strategy pattern就是將會變動的member function用class包起來,變成object『掛』在原本的class上。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.