設計模式(四) —- Factory 方法模式

來源:互聯網
上載者:User

絕大部分轉自:http://blog.csdn.net/zhengzhb/article/details/7359385

Factory 方法模式簡單來說就是將工廠裡建立對象的部分,抽象成虛類。這樣我們就可以降低工廠類方法內的邏輯。


     簡單原廠模式的最大優點在於工廠類中包含了必要的邏輯判斷,根據用戶端的選擇條件動態執行個體化相關的類,注意是相關的類,而不是僅僅一個類。

典型應用

       要說明原廠模式的優點,可能沒有比組裝汽車更合適的例子了。情境是這樣的:汽車由發動機、輪、底盤組成,現在需要組裝一輛車交給調用者。假如不使用原廠模式,代碼如下:

class Engine {public void getStyle(){System.out.println("這是汽車的發動機");}}class Underpan {public void getStyle(){System.out.println("這是汽車的底盤");}}class Wheel {public void getStyle(){System.out.println("這是汽車的輪胎");}}public class Client {public static void main(String[] args) {Engine engine = new Engine();Underpan underpan = new Underpan();Wheel wheel = new Wheel();ICar car = new Car(underpan, wheel, engine);car.show();}}

使用Factory 方法

interface IFactory {public ICar createCar();}class Factory implements IFactory {public ICar createCar() {Engine engine = new Engine();Underpan underpan = new Underpan();Wheel wheel = new Wheel();ICar car = new Car(underpan, wheel, engine);return car;}}public class Client {public static void main(String[] args) {IFactory factory = new Factory();ICar car = factory.createCar();car.show();}}



       可以看到,調用者為了組裝汽車還需要另外執行個體化發動機、底盤和輪胎,而這些汽車的組件是與調用者無關的,嚴重違反了迪米特法則(沒有直接關係,不出現在類內部。),耦合度太高。並且非常不利於擴充。另外,本例中發動機、底盤和輪胎還是比較具體的,在實際應用中,可能這些產品的組件也都是抽象的,調用者根本不知道怎樣組裝產品。假如使用Factory 方法的話,整個架構就顯得清晰了許多。 

       Factory 方法實現時,用戶端需要決定執行個體化哪一個工廠來實現。Factory 方法把所見但工廠內部的邏輯判斷移動到了用戶端,本來需要修改工廠類的,而現在只需要修改用戶端。降低了耦合。

聯繫我們

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