上篇我们讲了简单工厂模式,也提到了简单工厂模式的缺点,这篇我们来讲一下工厂方法模式,而工厂方法模式在一定程度上避免了简单工厂模式的那些缺点,废话不多说,上代码咯。
工厂方法模式:
以下代码在VS2012上编译通过
#include <iostream>
using namespace std;
class Product
{
public:
virtual void showProduct()
{cout<<"showProduct"<<endl;}
};
class ProductA:public Product
{
public:
void showProduct()
{
cout<<"showProductA"<<endl;
}
};
class ProductB:public Product
{
public:
void showProduct(){
cout<<"showProductB"<<endl;
}
};
class Factory
{
public:
virtual Product* createProduct()
{return NULL;}
};
class FactoryA: public Factory
{
public:
Product* createProduct()
{ return new ProductA(); }
};
class FactoryB:public Factory
{
public: Product* createProduct()
{ return new ProductB(); }
};
int _tmain(int argc, _TCHAR* argv[])
{
Factory* fa=new FactoryA();//创建生产A产品的工厂
Product* pa=fa->createProduct();//生产A产品
pa->showProduct();//显示A产品
Factory* fb=new FactoryB();//创建生产B产品的工厂
Product* pb=fb->createProduct();//生产B产品
pb->showProduct();//显示B产品
return 0;
}
执行结果:
showProductA
showProductB