factory模式,又称工厂模式。允许在不指定需要创建对象类型的情况下创建出对象。本质上来说,工厂方法就是一个通用的构造函数[1]。这种方法突破了像传统构建对象实例(Foo *f = new Foo())需要命名等诸多限制。
一个小例子即可说明好处:
class pruduct
{
...;
};
struct factory
{
product* CreateProduct()
{
return new product;
}
};
void use(product *)
{
...;
}
void main()
{
use(factory::CreateProduct);
}
注意的是return new 是返回创建实例的引用,也就是指针!
参考:
[1]http://www.cppblog.com/eryar/archive/2013/03/22/198738.html