最近看一本设计模式,自己抽空实现了一下,分享一下,最忌比较忙,就不细说了,先把代码放在这里,之后补上注释。
书上把设计模式分为创建型,结构型和行为型,本次先来创建型。
(一),抽象工厂模式AbsractFactory
头文件
#ifndef _ABS_FACTORY_H_
#define _ABS_FACTORY_H_
#include <string>
using namespace std;
//////////////////////////////////////////////////////////////////////////
// base
class Phone
{
public:
string m_strName;
virtual ~Phone();
};
class Computer
{
public:
string m_strName;
};
class AbstractFactory
{
public:
virtual Phone* CreatePhone() = 0;
virtual Computer* CreateComputer() = 0;
};
//////////////////////////////////////////////////////////////////////////
// apple
class iPhone:public Phone
{
public:
string m_strAssistName;
~iPhone();
};
class Mac:public Computer
{
// 偷个懒
};
class AppleFactory: public AbstractFactory
{
public:
virtual Phone* CreatePhone();
virtual Computer* CreateComputer();
};
//////////////////////////////////////////////////////////////////////////
//google
class Nexus:public Phone
{
public:
string m_strSysName;
};
class ChromeBook: public Computer
{
// 偷个懒
};
class GoogleFactory : public AbstractFactory
{
public:
virtual Phone* CreatePhone();
virtual Computer* CreateComputer();
};
void AbstractFactoryStartFunction();
#endif
1 实现
2
3 #include "AbsractFactory.h"
4 #include <iostream>
5
6 using namespace std;
7
8 #define RELEASE_OBJECT(pObj) {delete pObj; pObj = NULL;}
9
10 //google
11 Computer* GoogleFactory::CreateComputer()
12 {
13 ChromeBook* poChromeBook = new ChromeBook();
14 poChromeBook->m_strName = "ChromeBook";
15 return poChromeBook;
16 }
17
18 Phone* GoogleFactory::CreatePhone()
19 {
20 Nexus* poNexus = new Nexus();
21 poNexus->m_strSysName = "android";
22 poNexus->m_strName = "Nexus";
23 return poNexus;
24 }
25
26 //apple
27 Computer* AppleFactory::CreateComputer()
28 {
29 Mac* poMac = new Mac();
30 poMac->m_strName = "MacBook";
31 return poMac;
32 }
33
34 Phone* AppleFactory::CreatePhone()
35 {
36 iPhone* poIPhone = new iPhone();
37 poIPhone->m_strAssistName = "siri";
38 poIPhone->m_strName = "Nexus";
39 return poIPhone;
40 }
41
42 // 记得用虚析构函数哦
43 Phone::~Phone()
44 {
45 cout << "记得用虚析构函数哦" << endl;
46 }
47
48 iPhone::~iPhone()
49 {
50 cout << "Q: 会是否子类吗? A: yes" << endl;
51 }
52
53 //使用相同的流程,使用不同的工厂,生产不同的实例,(没检测空指针,不要像我学习 O(∩_∩)O~)
54 void GetProduct(AbstractFactory* poFactory, Phone*& poPhone, Computer*& poComputer)
55 {
56 poPhone = poFactory->CreatePhone();
57 poComputer = poFactory->CreateComputer();
58 }
59
60 void AbstractFactoryStartFunction()
61 {
62 AbstractFactory *poFactory = NULL;
63 Phone *poPhone = NULL;
64 Computer *poComputer = NULL;
65
66 // for apple
67 poFactory = new AppleFactory();// 生成特点类型的工厂用于生成实例
68 GetProduct(poFactory, poPhone, poComputer);//生产实例
69
70 cout << " PhoneName :" << poPhone->m_strName << endl;
71 cout << " PhoneAssistName :" << ((iPhone*)poPhone)->m_strAssistName << endl; //不同的产品有自己的特性
72 cout << " ComputerName :" << poComputer->m_strName << endl;
73
74 RELEASE_OBJECT(poFactory);
75 RELEASE_OBJECT(poPhone);
76 RELEASE_OBJECT(poComputer);
77
78 // for google
79 poFactory = new GoogleFactory(); // 改变的只有这里
80 GetProduct(poFactory, poPhone, poComputer);
81
82 cout << " PhoneName :" << poPhone->m_strName << endl;
83 cout << " PhoneSysName :" << ((Nexus*)poPhone)->m_strSysName << endl; //不同的产品有自己的特性
84 cout << " ComputerName :" << poComputer->m_strName << endl;
85
86 RELEASE_OBJECT(poFactory);
87 RELEASE_OBJECT(poPhone);
88 RELEASE_OBJECT(poComputer);
89 }
(二)制造器,builder
头文件
#ifndef _BUILDER_H_
#define _BUILDER_H_
#include <string>
#include <map>
#include <sstream>
using namespace std;
// 这个类不能,也不需要实例化
class SerializationBuilder
{
public:
virtual void Start() = 0;
virtual void AddCfg(string strKey, string strValue) = 0;
virtual void End() = 0;
virtual string GetResult();
protected:
stringstream m_strResult;
};
// *.text
class TextSerializationBuilder: public SerializationBuilder
{
public:
virtual void Start();
virtual void AddCfg(string strKey, string strValue);
virtual void End();
};
// *.ini
class IniSerializationBuilder: public SerializationBuilder
{
public:
virtual void Start();
virtual void AddCfg(string strKey, string strValue);
virtual void End();
};
// *.xml
class XmlSerializationBuilder: public SerializationBuilder
{
public:
virtual void Start();
virtual void AddCfg(string strKey, string strValue);
virtual void End();
};
// *.*
// 其实你还可以创建更多的builder而不需要修改老代码,比如json...
class Config
{
public:
Config();
void Serialization(SerializationBuilder& oBuilder);
private:
map<string, string> m_mapCfg;
};
void BuilderStartFunction();
#endif
实现
#include "Builder.h"
#include <iostream>
using namespace std;
string SerializationBuilder::GetResult()
{
return m_strResult.str();
}
//TextSerializationBuilder
void TextSerializationBuilder::Start()
{
m_strResult << "=============[ApplictionConfig BEG]============ " <<endl;
}
void TextSerializationBuilder::AddCfg( string strKey, string strValue )
{
m_strResult <<"[" << strKey << "]: " << strValue << endl;
}
void TextSerializationBuilder::End()
{
m_strResult << "=============[ApplictionConfig END]============ " <<endl;
}
//IniSerializationBuilder
void IniSerializationBuilder::Start()
{
m_strResult << "[ApplictionConfig] " <<endl;
}
void IniSerializationBuilder::AddCfg( string strKey, string strValue )
{
m_strResult << ";" << strKey << "\n" // 爱写注释的是好孩子(*^__^*) 嘻嘻……
<< strKey << "=" << strValue << endl;
}
void IniSerializationBuilder::End()
{
m_strResult << endl;
}
//XmlSerializationBuilder
void XmlSerializationBuilder::Start()
{
m_strResult << "<ApplictionConfig> " <<endl;
}
void XmlSerializationBuilder::AddCfg( string strKey, string strValue )
{
m_strResult << " <" << strKey << ">\n"
<< " " << strValue << "\n"
<< " </" << strKey << ">" << endl;
}
void XmlSerializationBuilder::End()
{
m_strResult << "</ApplictionConfig> " <<endl;
}
//Config
Config::Config()
{
m_mapCfg.clear();
m_mapCfg["AppName"] = "builder test";
m_mapCfg["IpAddress"] = "127.0.0.1";
m_mapCfg["TcpPort"] = "8888";
m_mapCfg["晚上吃啥"] = "想吃火锅啊!";
m_mapCfg["无聊备注"] = "为啥总有人说我写代码不正经呢?";
}
void Config::Serialization( SerializationBuilder& oBuilder )
{
oBuilder.Start();
map<string, string>::iterator iter = m_mapCfg.begin();
for (; iter != m_mapCfg.end(); iter++)
{
oBuilder.AddCfg(iter->first, iter->second);
}
oBuilder.End();
}
//BuilderStartFunction
void BuilderStartFunction()
{
Config oConfig;
SerializationBuilder* poBuidler = NULL;
poBuidler = new TextSerializationBuilder(); // <--只有这里有差异
oConfig.Serialization(*poBuidler); // 相同的操作不同结果
cout << poBuidler->GetResult() << endl;
delete poBuidler; poBuidler = NULL;
poBuidler = new IniSerializationBuilder();// <--只有这里有差异
oConfig.Serialization(*poBuidler);// 相同的操作不同结果
cout << poBuidler->GetResult() << endl;
delete poBuidler; poBuidler = NULL;
poBuidler = new XmlSerializationBuilder();// <--只有这里有差异
oConfig.Serialization(*poBuidler);// 相同的操作不同结果
cout << poBuidler->GetResult() << endl;
delete poBuidler; poBuidler = NULL;
cout << " 每次有新的需求不用改老代码,加个builder就好了,是不是很爽,要不要谁来加一个json的?" << endl;
}
(三)工厂 factory
头文件
#ifndef _FACTORY_H_
#define _FACTORY_H_
typedef enum
{
VEHICLE_CAR,
VEHICLE_TRUCK,
VEHICLE_BUS
}VEHICLE_TYPE_ENUM;
// 这里其实可以只定义一个基类,在定义若干子类型
typedef struct
{
unsigned int ulSitCount;
unsigned int ulWheelCount;
}Vehicle;
class VehicleFactory
{
public:
/************************************************************************/
/* 根据输入参数生产实例,也可以是静态的 */
/************************************************************************/
Vehicle* CreatVehicle(VEHICLE_TYPE_ENUM emType);
};
void FactoryStartFunction();
#endif
实现
#include "Factory.h"
#include <iostream>
using namespace std;
Vehicle* VehicleFactory::CreatVehicle(VEHICLE_TYPE_ENUM emType)
{
// 也可以返回子类,在真实环境中更为常见
Vehicle* poVehicle = new Vehicle();
if (NULL == poVehicle)
{
return NULL;
}
// 根据不同参数配置不同的实例
switch(emType)
{
case VEHICLE_CAR:
poVehicle->ulSitCount = 4;
poVehicle->ulWheelCount = 4;
break;
case VEHICLE_TRUCK:
poVehicle->ulSitCount = 2;
poVehicle->ulWheelCount = 6;
break;
case VEHICLE_BUS:
poVehicle->ulSitCount = 20;
poVehicle->ulWheelCount = 6;
break;
default:
delete poVehicle;
poVehicle = NULL;
}
return poVehicle;
}
void FactoryStartFunction()
{
VehicleFactory oFactory; // 如果CreatVehicle是静态的不需要这个,后面使用VehicleFactory::CreatVehicle
Vehicle* poTruck = oFactory.CreatVehicle(VEHICLE_TRUCK);
if (NULL == poTruck)
{
return;
}
cout << "Truck has " << poTruck->ulSitCount << " Seats and "
<< poTruck->ulWheelCount << " Wheels " << endl;
delete poTruck;
}
(四) 原型 prototype
头文件
#ifndef _PROTOTYPE_H_
#define _PROTOTYPE_H_
#include <string>
#include <map>
#include <iostream>
using namespace std;
class Prototype
{
public:
unsigned int m_ulPrice;
string m_strName;
Prototype(){};//又偷懒,不要学我
Prototype(Prototype& other);
virtual Prototype* Clone() = 0;
virtual void Show() = 0;
};
class YouTiao: public Prototype
{
public:
YouTiao();
virtual Prototype* Clone();
virtual void Show();
};
class DouJiang: public Prototype
{
public:
DouJiang();
virtual Prototype* Clone();
virtual void Show();
};
class Bread: public Prototype
{
public:
Bread();
virtual Prototype* Clone();
virtual void Show();
};
class Milk: public Prototype
{
public:
Milk();
virtual Prototype* Clone();
virtual void Show();
};
class PrototypeManage
{
public:
void Clear();
void Init(int iFoodKey, Prototype* poFood, int iDrinkKey, Prototype *poDirnk);
Prototype* GetCopy(int iKey);
void InitChineseBreakfirst();
void InitEnglishBreakfirst();
private:
map<int, Prototype*> m_mapProtypes;
};
void PrototypeStartFunction();
#endif
实现
#include "Prototype.h"
//Prototype
Prototype::Prototype( Prototype& other )
{
m_ulPrice = other.m_ulPrice;
m_strName = other.m_strName;
}
// YouTiao
YouTiao::YouTiao()
{
m_strName = "油条";
m_ulPrice = 1;
}
Prototype* YouTiao::Clone()
{
return new YouTiao(*this);
}
void YouTiao::Show()
{
cout << "我是" << m_strName <<" 价格:" << m_ulPrice << "元" <<endl;
}
// DouJiang
DouJiang::DouJiang()
{
m_strName = "豆浆";
m_ulPrice = 2;
}
Prototype* DouJiang::Clone()
{
return new DouJiang(*this);
}
void DouJiang::Show()
{
cout << "我是" << m_strName <<" 价格:" << m_ulPrice << "元" <<endl;
}
// Bread
Bread::Bread()
{
m_strName = "Bread";
m_ulPrice = 3;
}
Prototype* Bread::Clone()
{
return new Bread(*this);
}
void Bread::Show()
{
cout << "This is " << m_strName <<" price: $" << m_ulPrice << endl;
}
//Milk
Milk::Milk()
{
m_strName = "Milk";
m_ulPrice = 5; //米国东西就是贵
}
Prototype* Milk::Clone()
{
return new Milk(*this);
}
void Milk::Show()
{
cout << "This is " << m_strName <<" price: $" << m_ulPrice << endl;
}
//PrototypeManage
void PrototypeManage::Clear()
{
map<int, Prototype*>::iterator iter = m_mapProtypes.begin();
for (;iter != m_mapProtypes.end(); iter++)
{
delete iter->second;
}
m_mapProtypes.clear();
}
void PrototypeManage::Init( int iFoodKey, Prototype* poFood, int iDrinkKey, Prototype *poDirnk )
{
Clear();
m_mapProtypes[iFoodKey] = poFood;
m_mapProtypes[iDrinkKey] = poDirnk;
}
Prototype* PrototypeManage::GetCopy( int iKey )
{
if (m_mapProtypes.find(iKey) == m_mapProtypes.end())
{
return NULL;
}
return m_mapProtypes[iKey]->Clone();
}
void PrototypeManage::InitChineseBreakfirst()
{
Init(0 , new YouTiao(), 1 ,new DouJiang());
}
void PrototypeManage::InitEnglishBreakfirst()
{
Init(0 , new Bread(), 1 ,new Milk());
}
void Sell(int aiSellList[], int iListLen,PrototypeManage& oPrototypeManage)
{
for (int i = 0; i < iListLen; i++)
{
Prototype* poItem = oPrototypeManage.GetCopy(aiSellList[i]);
poItem->Show();
delete poItem;
}
}
//PrototypeStartFunction
void PrototypeStartFunction()
{
int aiSellList[] = {0, 1, 1, 0, 1, 0 }; // 我们需要很多的实例,但是不用每次都创建他们,配置他们,只要从原型中复制一下就好
PrototypeManage oPrototypeManage;
oPrototypeManage.InitChineseBreakfirst();
Sell(aiSellList, sizeof(aiSellList)/sizeof(int), oPrototypeManage);
oPrototypeManage.InitEnglishBreakfirst(); // 重新设置原型
Sell(aiSellList, sizeof(aiSellList)/sizeof(int), oPrototypeManage);//同样的操作产生了很不相同的结果,这是原型的好处之一:动态更换原型
}
(五)单例
头文件
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <string>
#include <map>
#include <iostream>
using namespace std;
typedef enum
{
CAR_FACTORY,
}FACTORTY_TYPE;
class Singleton
{
public:
static Singleton* GetInstance(FACTORTY_TYPE emType);
protected:
Singleton();
private:
static Singleton* s_poInstance;
};
class CarFactory: public Singleton
{
public:
void GetNewCar();
};
void SingletonStartFunction();
#endif
实现
#include "Singleton.h"
Singleton* Singleton::s_poInstance = NULL; //C++ 的静态变量复制比较奇怪
Singleton* Singleton::GetInstance(FACTORTY_TYPE emType)
{
switch (emType)
{
case CAR_FACTORY:
if (NULL == s_poInstance)
{
s_poInstance = new CarFactory();
}
break;
default:
cout << "unknow type :" << emType << endl;
break;
}
return s_poInstance;
}
Singleton::Singleton()
{
}
void CarFactory::GetNewCar()
{
cout << "build a new cat" << endl;
}
void SingletonStartFunction()
{
CarFactory *poFactory = (CarFactory*)Singleton::GetInstance(CAR_FACTORY);
poFactory->GetNewCar();
}
顺便把main函数附上大家可以自己操练下:
#include <iostream>
#include <string>
#include "Factory/Factory.h"
#include "AbsractFactory/AbsractFactory.h"
#include "Builder/Builder.h"
#include "Prototype/Prototype.h"
#include "Singleton/Singleton.h"
#include "Adapter/Adapter.h"
#include "Bridge/Bridge.h"
using namespace std;
typedef void (*PF_StartFunc)();
typedef enum
{
DP_FACTORY,
DP_ABSTRACT_FACTORY,
DP_BUILDER,
DP_PROTOTYPE,
DP_SINGLENTON,
DP_ADAPTER,
DP_BRIDGE
}DP_TYPE;
typedef struct
{
DP_TYPE emType;
PF_StartFunc pfStartFunction;
}DP_START_FUNC;
DP_START_FUNC g_astDesignPatterns[] = {
{DP_FACTORY, FactoryStartFunction },
{DP_ABSTRACT_FACTORY, AbstractFactoryStartFunction},
{DP_BUILDER, BuilderStartFunction },
{DP_PROTOTYPE, PrototypeStartFunction },
{DP_SINGLENTON, SingletonStartFunction },
{DP_ADAPTER, AdapterStartFunction },
{DP_BRIDGE, BridgeStartFuction}
};
PF_StartFunc GetStartFunc(DP_TYPE emType)
{
size_t uPatternCount = sizeof(g_astDesignPatterns)/sizeof(DP_START_FUNC);
for (size_t u = 0; u < uPatternCount; u++)
{
if (g_astDesignPatterns[u].emType == emType)
{
return g_astDesignPatterns[u].pfStartFunction;
}
}
return NULL;
}
int main()
{
DP_TYPE emType = DP_BRIDGE; //每次测试修改这里就可以了
PF_StartFunc pfStartFunc = GetStartFunc(emType);
if (NULL == pfStartFunc)
{
cout << "emType[" << emType <<"]" << "not have start function" << endl;
return 1;
}
(*pfStartFunc)();
system("pause");
return 0;
}