Java設計模式(2)——Factory 方法模式

來源:互聯網
上載者:User

標籤:system   pos   ring   main   執行個體化   rgs   ace   子類   圖片   

  Factory 方法模式同樣屬於類的建立型模式又被稱為多態原廠模式。Factory 方法模式的意義是定義一個建立產品對象的工廠介面,將實際建立工作延遲到子類當中。核心工廠類不再負責產品的建立,這樣核心類成為一個抽象工廠角色,僅負責具體工廠子類必須實現的介面,這樣進一步抽象化的好處是使得Factory 方法模式可以使系統在不修改具體工廠角色的情況下引進新的產品。

一、模式中包含的角色及其職責

1.抽象工廠(Creator)角色
  Factory 方法模式的核心,任何工廠類都必須實現這個介面。
2.具體工廠( Concrete Creator)
  角色具體工廠類是抽象工廠的一個實現,負責執行個體化產品對象。
3.抽象(Product)角色
  Factory 方法模式所建立的所有對象的父類,它負責描述所有執行個體所共有的公用介面。
4.具體產品(Concrete Product)角色
  Factory 方法模式所建立的具體執行個體對象

二、Factory 方法模式和簡單原廠模式的比較
  1. Factory 方法模式與簡單原廠模式在結構上的不同不是很明顯。Factory 方法類的核心是一個抽象工廠類,而簡單原廠模式把核心放在一個具體類上。
  2. Factory 方法模式之所以有一個別名叫多態性原廠模式是因為具體工廠類都有共同的介面,或者有共同的抽象父類。
  3. 當系統擴充需要添加新的產品對象時,僅僅需要添加一個具體對象以及一個具體工廠對象,原有工廠對象不需要進行任何修改,也不需要修改用戶端,很好的符合了“開放-封閉”原則。而簡單原廠模式在添加新產品對象後不得不修改Factory 方法,擴充性不好。
  4. Factory 方法模式退化後可以演變成簡單原廠模式。
三、Demo抽象角色
public interface Fruit {    /*     * 採集     */    public void get();}
具體產品
public class Apple implements Fruit{    /*     * 採集     */    public void get(){        System.out.println("採集蘋果");    }}
public class Banana implements Fruit{    /*     * 採集     */    public void get(){        System.out.println("採集香蕉");    }}
抽象工廠角色
public interface FruitFactory {    public Fruit getFruit();}
具體工廠
public class AppleFactory implements FruitFactory {    public Fruit getFruit() {        return new Apple();    }}
public class BananaFactory implements FruitFactory {    public Fruit getFruit() {        return new Banana();    }}
測試方法
public class MainClass {    public static void main(String[] args) {        //獲得AppleFactory        FruitFactory ff = new AppleFactory();        //通過AppleFactory來獲得Apple執行個體對象        Fruit apple = ff.getFruit();        apple.get();                //獲得BananaFactory        FruitFactory ff2 = new BananaFactory();        Fruit banana = ff2.getFruit();        banana.get();            }}
控制台輸出
採集蘋果採集香蕉
四、UML類圖

Java設計模式(2)——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.