阅读之前期望你已经懂得模板方法模式及单例模式的原理。通俗软件设计模式的表述呈现由GoF先行打响头炮,其后各种版本的模式书籍层出不穷,大多示范实现都是以有多态特性的虚函数作为核心,每一个virtual function call是间接进行的,如此一来性能会有小小的损耗,但可读性良好,尤其在配合UML静态类图的情况下,各种模式可谓过目难忘。通过浏览一些水准高超的C++库发现,其实这些性能优异稳定的库是离不开模板的,当然可读性又大打折扣了。怎样权衡利用模板,各人有各人的看法,废话不多说了,本文明显是偏向模板的使用的,通过两个模式的模板简化实现,展示范型的风采,你可以在此基础上加以深化并应用于实际项目中。
其实下面的模式实现技巧在一些团队中会被称为“基类参数化”。
因何得名?请结合代码自行体会。
header file:
#ifndef BASEPARAM_HEADER_
#define BASEPARAM_HEADER_
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
//Template Method Pattern
template<typename T>
class Base : public T
{
public:
void templateMethod(string& str)
{
T::hookMethod1();
T::hookMethod2(str);
T::hookMethod3();
}
};
class CFileLog
{
public:
void hookMethod1()
{
cout<<"1. open file"<<endl;
}
void hookMethod2(string& str)
{
cout<<"2. log to file: "<<str<<endl;
}
void hookMethod3()
{
cout<<"3. close file"<<endl;
}
};
class CDatabaseLog
{
public:
void hookMethod1()
{
cout<<"1. open database"<<endl;
}
void hookMethod2(string& str)
{
cout<<"2. log to database: "<<str<<endl;
}
void hookMethod3()
{
cout<<"3. close database"<<endl;
}
};
//Singleton Pattern (not thread-safe)
template<typename T>
class CSingleton
{
public:
static T* instance()
{
if (thiz == NULL)
{
thiz = new T();
}
return thiz;
}
protected:
CSingleton(){}
static T* thiz;
};
template<typename T>
T* CSingleton<T>::thiz = NULL;
class CLog:public CSingleton<CLog>
{
public:
void debug(string& str)
{
cout<<this<<" : "<<str<<endl;
}
};
#endif //BASEPARAM_HEADER_
cpp file:
#include "stdafx.h"
#include "baseparam.h"
int _tmain(int argc, _TCHAR* argv[])
{
string log("hello, world!");
//这里是Template Method实现以不同的persistence技术进行写日志的应用例子
Base<CFileLog> log1;
log1.templateMethod(log);
Base<CDatabaseLog> log2;
log2.templateMethod(log);
cout<<endl;
//这里是Singleton实现的例子
CLog::instance()->debug(log);
CLog::instance()->debug(log);
CLog::instance()->debug(log);
CLog::instance()->debug(log);
CLog::instance()->debug(log);
system("pause");
return 0;
}