最近有点空闲,就总结一下编程中遇到的设计模式吧,也算是增强一下记性。
首先我们说一下工厂模式,这个工厂模式呢,又分为简单工厂模式、工厂方法模式(多态工厂模式)、抽象工厂模式这三种,这三种我都会陆续讲到。
简单工厂模式:
以下设计模式代码均在VS2012上编译通过:
#include <iostream>
using namespace std;
enum productName{pA,pB};
class Product
{
public:
virtual void showProduct()
{cout<<"show Product"<<endl;}
};
class ProductA:public Product
{
public:
void showProduct()
{
cout<<"show ProductA"<<endl;
}
};
class ProductB:public Product
{
public:
void showProduct(){
cout<<"show ProductB"<<endl;
}
};
class Factory
{
public:
static Product* createProduct(productName name)
{
switch(name)
{
case pA: return new ProductA();
case pB: return new ProductB();
default: return NULL ;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Factory fac;//创建工厂
Product* pa=fac.createProduct(pA);//生产A产品
pa->showProduct();//显示A产品
Product* pb=fac.createProduct(pB);//生产B产品
pb->showProduct();//显示B产品
return 0;
}
执行结果:
show ProductAshow ProductB
1502

被折叠的 条评论
为什么被折叠?



