// 工厂方法
/*
意图: 定义一个接口,让其子类决定实例化那个类,使一个类的实例化延迟到子类
别名: 虚构造器
动机:
*/
/*
#include <iostream>
using namespace std;
class IUser
{
public:
virtual void InsertData() = 0;
virtual void GetUser() = 0;
};
class CSqlUser:public IUser
{
public:
void InsertData(){cout<<"This is CSqlUser InsertData"<<endl;};
void GetUser(){cout<<"This is CSqlUser GetUser"<<endl;};
};
class CAccUser: public IUser
{
public:
void InsertData(){cout<<"This is CAccUser InsertData"<<endl;};
void GetUser(){cout<<"This is CAccUser GetUser"<<endl;};
};
//IUser * pUser;
class IFactory
{
public:
IUser *CreateUser();
};
class CSqlFactory
{
public:
CSqlFactory(){};
CSqlUser * CreateUser()
{
m_SqlUser = new CSqlUser();
return m_SqlUser;
};
private:
CSqlUser* m_SqlUser;
};
class CAccFactory
{
public:
CAccFactory(){};
CAccUser * CreateUser()
{
m_AccUser = new CAccUser();
return m_AccUser;
};
private:
CAccUser* m_AccUser;
};
int main()
{
CSqlFactory sql;
IUser *puser;
puser = sql.CreateUser();
puser->GetUser();
CAccFactory acc;
puser = acc.CreateUser();
puser->GetUser();
return 0;
}
*/
// 简单工厂方法
#include <iostream>
using namespace std;
class Human
{
public:
virtual void laugh() = 0;
virtual void cry() = 0;
virtual void talk() = 0;
};
class YellowHuman:public Human
{
public:
YellowHuman(){cout<<"This is YellowHuman Constrator!"<<endl;};
void laugh(){cout<<"This is YellowHuman laugh"<<endl;};
void cry(){cout<<"This is YellowHuman cry"<<endl;}
void talk(){cout<<"This is YellowHuman talk"<<endl;};
};
class WhiteHuman:public Human
{
public:
WhiteHuman(){cout<<"This is WhiteHuman Constrator!"<<endl;};
void laugh(){cout<<"This is WhiteHuman laugh"<<endl;};
void cry(){cout<<"This is WhiteHuman cry"<<endl;}
void talk(){cout<<"This is WhiteHuman talk"<<endl;};
};
class BleakHuman:public Human
{
public:
BleakHuman(){cout<<"This is BleakHuman Constrator!"<<endl;};
void laugh(){cout<<"This is BleakHuman laugh"<<endl;};
void cry(){cout<<"This is BleakHuman cry"<<endl;}
void talk(){cout<<"This is BleakHuman talk"<<endl;};
};
class HumanFactory
{
public:
Human* CreateHuman(int num)
{
switch( num)
{
case 0:
phuman = new YellowHuman();
break;
case 1:
phuman = new WhiteHuman();
break;
case 2:
phuman = new BleakHuman();
break;
}
return phuman;
}
private:
Human *phuman;
};
int main()
{
Human *phuman;
HumanFactory factory;
phuman = factory.CreateHuman(0);
phuman->cry();
phuman->talk();
phuman->laugh();
return 0;
}