一、使用意图
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
二、UML图
三、组织结构(building blocks)
(1)AbstractFactory (WidgetFactory)
declares an interface for operations that create abstract product objects.
(2)ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)
implements the operations to create concrete product objects.
(3)AbstractProduct (Window, ScrollBar)
declares an interface for a type of product object.
(4)ConcreteProduct (MotifWindow, MotifScrollBar)
- defines a product object to be created by the corresponding concrete factory.
- implements the AbstractProduct interface.
(5)Client
uses only interfaces declared by AbstractFactory and AbstractProduct classes.
四、特性
(1)AbstractFactory defers creation of product objects to its ConcreteFactory subclass.
(2)Product class names are isolated in the implementation of the concrete factory; they do not appear in client code.
(3)It makes exchanging product families easy.
(4)Supporting new kinds of products is difficult.
Supporting new kinds of products requires extending the factory interface, which involves changing the AbstractFactory class and all of its subclasses.
见实现注意点中的(3)。
五、实现注意点
(1)Factories as singletons.
An application typically needs only one instance of a ConcreteFactory per product family.
(2)Creating the products.
AbstractFactory only declares an interface for creating products. It’s up to ConcreteProduct subclasses to actually create them.
The most common way to do this is to define a factory method (see Factory Method (121)) for each product. A concrete factory will specify its products by overriding the factory method for each.
Notice that the MazeFactory is just a collection of factory methods. This is the most common way to implement the Abstract Factory pattern.
(3)Defining extensible factories.
AbstractFactory usually defines a different operation for each kind of product it can produce. The kinds of products are encoded in the operation signatures. Adding a new kind of product requires changing the AbstractFactory interface and all the classes that depend on it.
例子:假设抽象工厂作用是生产交通工具,原先可以生产汽车和自行车,现在要它可以新生产摩托车,则需要改抽象工厂的interface。
A more flexible but less safe design is to add a parameter to operations that create objects. This parameter specifies the kind of object to be created. It could be a class identifier, an integer, a string, or anything else that identifies the kind of product.(注:简单工厂模式.)但这种方法的缺点是:这种做法只需要一个Create函数。The client will not be able to differentiate or make safe assumptions about the class of a product. 例如爆炸房间有自己独有的方法,则必须把Room* downcast成BombedRoom*,因为Room类没有这个方法。
六、相关设计模式
AbstractFactory classes are often implemented with factory methods (Factory Method (121)), but they can also be implemented using Prototype (133).
A concrete factory is often a singleton (Singleton (144))
七、参考资料
[1] GoF设计模式
[2] C++ 抽象工厂模式 作者:一去丶二三里