C/Cpp / 设计模式 / 简单工厂模式

---------------------------------------------
-- 时间:2019-03-19
-- 创建人:Ruo_Xiao
-- 邮箱:xclsoftware@163.com
---------------------------------------------

一、实质

        本质是工厂实例创建并输出产品类实例的过程。

二、栗子

1、产品类(抽象类):汽车

#ifndef __VirtualCar_H__
#define __VirtualCar_H__

#include <iostream>
using namespace std;

class VirtualCar
{
public:
	VirtualCar(void){};
	virtual ~VirtualCar(void){};
public:
	virtual string CarName() = 0;
};
#endif

2、产品实例:具体汽车

#ifndef __AudiCar_H__
#define __AudiCar_H__

#include "../VirtualCar/VirtualCar.h"
class AudiCar :	 public VirtualCar
{
public:
	AudiCar(void){};
	~AudiCar(void){};
public:
	string CarName()
	{
		return "My name is Audi!";
	}
};

#endif

 

#ifndef __PorscheCar_H__
#define __PorscheCar_H__

#include "../VirtualCar/VirtualCar.h"
class PorscheCar :  public VirtualCar
{
public:
	PorscheCar(void){};
	~PorscheCar(void){};
public:
	string CarName()
	{
		return "My name is Porsche!";
	}
};

#endif
#ifndef __BenzCar_H__
#define __BenzCar_H__

#include "../VirtualCar/VirtualCar.h"

class BenzCar : public VirtualCar
{
public:
	BenzCar(void){};
	~BenzCar(void){};
public:
	string CarName()
	{
		return "My name is Benz!";
	}
};

#endif

 3、工厂:汽车工厂

#ifndef __CarFactory_H__
#define __CarFactory_H__

#include "../VirtualCar/VirtualCar.h"
#include "../AudiCar/AudiCar.hpp"
#include "../BenzCar/BenzCar.hpp"
#include "../PorscheCar/PorscheCar.hpp"

class CarFactory
{
public:
	CarFactory(void)
	{
		pAudi		=	new AudiCar();
		pBenz		=	new BenzCar();
		pPorsche	=	new PorscheCar();
	}
	~CarFactory(void)
	{
		delete pAudi;		pAudi		=	nullptr;
		delete pBenz;		pBenz		=	nullptr;
		delete pPorsche;	pPorsche	=	nullptr;
	}
private:
	AudiCar		*pAudi;
	BenzCar		*pBenz;
	PorscheCar	*pPorsche;
public:
	VirtualCar *GetCar(int iMode)
	{
		switch (iMode)
		{
		case 1:
			return pAudi;
		case 2:
			return pBenz;
		case 3:
			return pPorsche;
		}
		return nullptr;
	}
};

#endif

4、客户端

#include<iostream>
#include<string>
using namespace std;

#include "source\VirtualCar\VirtualCar.h"
#include "source\CarFactory\CarFactory.hpp"

int main() 
{	
	VirtualCar *pCarBase;
	CarFactory CarAll;

	pCarBase = CarAll.GetCar(1);
	cout<<pCarBase->CarName()<<endl;

	pCarBase = CarAll.GetCar(2);
	cout<<pCarBase->CarName()<<endl;

	pCarBase = CarAll.GetCar(3);
	cout<<pCarBase->CarName()<<endl;

	cin.get();
	return 0;
}

6、结果:

三、源码工程

https://download.csdn.net/download/itworld123/11036841

 

(SAW:Game Over!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值