主要用来解决两个问题
1.将类创建的实例延迟到子类
2.提供类创建接口(将project创建以factory接口形式给出)
factory.h
#ifndef _FACTORY_H
#define _FACTORY_H
#include <iostream>
using namespace std;
class Product
{
public:
virtual ~Product() {};
protected:
Product() {}
};
class RealProduct : public Product
{
public:
RealProduct() {
cout << "RealProduct" << endl;
}
~RealProduct() {}
};
class Factory
{
public:
virtual ~Factory() {}
virtual Product* CreateProduct()=0;
protected:
Factory() {}
};
class RealFactory : public Factory
{
public:
RealFactory() {}
~RealFactory() {}
Product* CreateProduct() {
return new RealProduct;
}
};
#endif // _FACTORY_H
factory.cpp
#include "factory.h"
int main()
{
RealFactory *f = new RealFactory;
f->CreateProduct();
return 0;
}
编译:make factory