工厂模式更像是将简单工厂模式在开闭原则的情况(对修改关闭对新加开放)进行了修改。
#include <iostream>
#include <string>
using namespace std;
/* 工厂模式
* 工厂模式就是定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使
* 一个类的实例化延迟到子类。
* 工厂模式和简单工厂模式的区别,简单工厂模式是通过客户端传入type,在简单工厂类中动态
* 生成该对象。而工厂模式是通过客户端自己生成一个对象。
*/
class CLeiFeng
{
public:
CLeiFeng() {}
virtual ~CLeiFeng() {}
void Wash() { cout << "洗衣服" << endl; }
virtual void DoSpecial() = 0;
};
class CUndergradute : public CLeiFeng
{
public:
CUndergradute() {}
virtual void DoSpecial() { cout << "读书" << endl; }
};
class CVolunteer : public CLeiFeng
{
public:
CVolunteer() {}
virtual void DoSpecial() { cout << "拖地" << endl; }
};
class IFactory
{
public:
IFactory() {}
virtual CLeiFeng* CreateLeiFeng() = 0;
};
class CUndergraduteFactory : public IFactory
{
public:
CUndergraduteFactory() {}
virtual CLeiFeng* CreateLeiFeng() {
return new (std::nothrow) CUndergradute();
}
};
class CVolunteerFactory : public IFactory
{
public:
CVolunteerFactory() {}
virtual CLeiFeng* CreateLeiFeng()
{
return new (std::nothrow) CVolunteer();
}
};
int main()
{
IFactory* pfactory = new CVolunteerFactory();
if (nullptr == pfactory)
{
cout << "" << endl;
return -1;
}
CLeiFeng* pLeiFeng = pfactory->CreateLeiFeng();
pLeiFeng->DoSpecial();
delete pLeiFeng;
delete pfactory;
}