---------------------------------------------
-- 时间: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!)