设计模式 之 工厂模式
时间:2010-08-04 来源:kokokowy
#include <iostream>
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;
}
* 产品类
*/
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;
}
相关阅读 更多 +