现在的位置: 首页 > 综合 > 正文

单例模式(2)—模板类实现

2014年02月02日 ⁄ 综合 ⁄ 共 716字 ⁄ 字号 评论关闭

下面来用一个简单的实例来实现模板类的单例模式:

singleton.h

#include <iostream>

template<typename T> 
class Singleton
{
	public:
		static T& Instance()		// 通过静态公有函数过的该实例
		{
			static T pInstance;
			return pInstance;
		}
	protected:
		Singleton(){}
		
	private:
		// Prohibited actions...this does not prevent hijacking.
                Singleton(const Singleton &);
                Singleton& operator=(const Singleton &);
		
		class Garbo
		{
		public:
			~Garbo()
			{
				if (Singleton::m_pInstance)
					delete Singleton::m_pInstance;
			}
		};
		
		static Garbo garbo;
};

test.h

#include "singleton.h"

class Test : public Singleton<Test>
{
       public:
                void outString(){
                        printf("This is test for singleton\n");
};

#define sTest   Singleton<Test>::Instance()

main.cpp

#include "test.h"

int main(int argc, char *argv[])
{
       sTest.outString();
       return 0;
}

本例只是实现了显示一个字符串的功能,如需其他操作只需要在Test类里面添加就可以访问,且只写出本例的头文件,其他系统头文件须自行调用。

 

抱歉!评论已关闭.