模板强化Template Method & Singleton 模式

 阅读之前期望你已经懂得模板方法模式及单例模式的原理。通俗软件设计模式的表述呈现由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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值