一、使用意图
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
二、什么时候使用
- A class can’t anticipate the class of objects it must create.
- A class wants its subclasses to specify the objects it creates.
- Classes delegate responsibility to one of several helper subclasses, and
you want to localize the knowledge of which helper subclass is the delegate.
三、UML图
四、组织结构(building blocks)
- Product (Document)
defines the interface of objects the factory method creates. - ConcreteProduct (MyDocument)
implements the Product interface. - Creator (Application)
- declares the factory method, which returns an object of type Product.
Creator may also define a default implementation of the factory
method that returns a default ConcreteProduct object. - may call the factory method to create a Product object.
- ConcreteCreator (MyApplication)
overrides the factory method to return an instance of a ConcreteProduct.
五、特性
(1) Creating objects inside a class with a factory method is always more flexible than creating an object directly.
(2) Connects parallel class hierarchies.
可以通过subclass一个抽象工厂得到多个具体工厂,来生产近似的产品。
例子:p124图
六、实现注意点
(1) Creator的factory method是否要有默认实现,还是纯虚函数
(2) 带参数的facory method(也称简单工厂模式)
The factory method takes a parameter that identifies the kind of object to create.
代码例:
class Creator {
public:
virtual Product* Create(ProductID id);
};
Product* Creator::Create(ProductID id)
{
if (id == MINE)
return new MyProduct;
if (id == YOURS)
return new YourProduct;
// repeat for remaining products...
return 0;
}
(3) C++实现注意点
Factory methods in C++ are always virtual functions and are often pure virtual. Just be careful not to call factory methods in the Creator’s constructor—the factory method in the ConcreteCreator won’t be available yet.
Instead of creating the concrete product in the constructor, the constructor merely initializes it to 0. The accessor returns the product. But first it checks to make sure the product exists, and if it doesn’t, the accessor creates it. This technique is sometimes called lazy initialization.
代码例:
class Creator {
public:
Product* GetProduct();
protected:
virtual Product* CreateProduct();
private:
Product* _product;
};
Product* Creator::GetProduct ()
{
if (_product == nullptr)
{
_product = CreateProduct();
}
return _product;
}
七、相关设计模式
Abstract Factory (99) is often implemented with factory methods. The Motivation example in the Abstract Factory pattern illustrates Factory Method as well.
Factory methods are usually called within Template Methods (360). In the document example above, NewDocument is a template method.
Prototypes (133) don’t require subclassing Creator. However, they often require an Initialize operation on the Product class. Creator uses Initialize to initialize the object. Factory Method doesn’t require such an operation.
八、参考资料
[1] GoF设计模式
[2] C++工厂模式方法 作者:一去丶二三里