1. 程式人生 > >建立型模式--抽象工廠模式(Abstract Factory)

建立型模式--抽象工廠模式(Abstract Factory)

Abstract Factory:Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

抽象工廠(Abstract Factory)模式是所有工廠模式中最抽象和最具有一般性的形態,和工廠方法模式的最大區別在於,工廠方法模式針對的是一個產品等級結構,而抽象工廠模式則需要對多個產品等級結構。

一:引入

         最早起源應用於不通作業系統的視窗構件,如一個Button類在windows環境和unix環境下有對應的實現,如果使用工廠方法模式,需要每個Concrete Product類對應一個Concrete Factory,在太多構件的情況下顯然不合適。

         改為有兩個Concrete Factory(因為有兩大類(當然也可以有多個類)),每個Factory類負責建立這一類的所有物件。

publicclass WinFactory implements AbstractFactory...{
    
public Button createButton()
    
...{
        
returnnew WinButton();
    }

    
public Text createText()
    
...{
        
returnnew WinText();
    }

}


publicclass UnixFactory implements
 AbstractFactory...{
    
public Button createButton()
    
...{
        
returnnew UnixButton();
    }

    
public Text createText()
    
...{
        
returnnew UnixText();
    }

}

二:結構

三:實際應用

  1. 最早起源應用於不通作業系統的視窗構件。

四:適用情形

Use the Abstract Factory pattern when

a system should be independent of how its products are created, composed, and represented. a system should be configured with one of multiple families of products. a family of related product objects is designed to be used together, and you need to enforce this constraint. you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

參考文獻:

1:閻巨集,《Java與模式》,電子工業出版社
2:Eric Freeman & Elisabeth Freeman,《Head First Design Pattern》,O'REILLY