#include
using namespace std;
/*
* 产品类
*/
class CBaseProduct
{
public:
virtual void Print() = 0;
};
class CDeriveProductOne:public CBaseProduct
{
public:
virtual void Print()
{
cout << "hello one" << endl;
}
};
class CDeriveProductTwo:public CBaseProduct
{
public:
virtual void Print()
{
cout << "hello Two" << endl;
}
};
/*
* 工厂类
*/
class CBaseFactory
{
public:
virtual CBaseProduct * MakeProduct(int) = 0;
};
class CDeriveFactory:public CBaseFactory
{
public:
virtual CBaseProduct * MakeProduct(int iFlag);
};
/*
* 生产产品子类的实例函数
*/
CBaseProduct *
CDeriveFactory::MakeProduct(int iFlag)
{
CBaseProduct *pProduct = NULL;
try
{
switch(iFlag)
{
case 1:
pProduct = new CDeriveProductOne();
break;
case 2:
pProduct = new CDeriveProductTwo();
break;
default:
throw(0);
}
}
catch(...)
{
cout << "new obj failed" << endl;
}
return pProduct;
}
int main()
{
CBaseProduct *p = NULL;
CBaseFactory *f = new CDeriveFactory();
p = f->MakeProduct(2);
p->Print();
return 0;
}
阅读(662) | 评论(0) | 转发(0) |