简单工厂模式,和工厂方法模式

本文详细解释了工厂方法模式与简单工厂方法的概念、实现方式,并通过代码示例展示了如何在C++中应用这两种模式来创建不同类型的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


// 工厂方法
/*
意图: 定义一个接口,让其子类决定实例化那个类,使一个类的实例化延迟到子类
别名: 虚构造器
动机:

*/


/*
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值