创建型模式--抽象工厂模式(Abstract Factory)

    技术2022-05-11  41

    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类负责创建这一类的所有对象。

    public   class  WinFactory  implements  AbstractFactory {    public Button createButton()    {        return new WinButton();    }    public Text createText()    {        return new WinText();    }} public   class  UnixFactory  implements  AbstractFactory {    public Button createButton()    {        return new UnixButton();    }    public Text createText()    {        return new UnixText();    }}

     

    二:结构

    三:实际应用

    最早起源应用于不通操作系统的视窗构件。

     

    四:适用情形

    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

     

    最新回复(0)