C++设计模式:Singleton的模板实现之一 (转)

本文介绍了一种使用C++模板实现Singleton设计模式的方法,并提供了完整的代码示例。该实现支持线程安全创建单例对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++设计模式:Singleton的模板实现之一 (转)[@more@]

题目:C++设计模式:Singleton的模板实现之一
类型:原创

作者:古斌亮
时间:2002.12.25
EMail : Linux@163.com">KingLinux@163.com

 在.NET/">http://www.youkuaiyun.com/ 和天极网 看了两篇关于设计模式:Singleton的C++实现的文章,
自觉的学到不少东西(:)),在这里我也写了一个C++模板的实现之一,望各位大虾多多指教,也希望可以达到抛砖引玉的作用.

 关于的Singleton的原理可以参考天极网《C++设计模式之Singleton》或http://www.youkuaiyun.com/中的《Singleton模式的C++实现研究》或是书本《设计模式》,这里就不说了,请多包涵!

 翠花,上代码!

/////////////////////////////////
//singleton template file
//SingleEx.h

#ifndef SINGLETONEX__H__
#define SINGLETONEX__H__

//File Name : SingletonEx.h
//作用  : 提供单件模板功能(singleton template)
//Copyright(C) C++
//microsoft Visual C++ 6.0 , GCC Ver2.95.3-6 编译通过
//作者:古斌亮
//时间:2002.12.25
//email : KingLinux@163.com

template
class CSingletonBase
{
protected:
 inline static T* Create(void)
 {
 if(m_pt==NULL)
 {
 m_pt=new T();
 }
 return m_pt;
 }

 inline static void Free(void)
 {
 delete m_pt;
 m_pt=NULL;
 }

protected:
 CSingletonBase()
 {
 }

 virtual ~CSingletonBase()
 {
 delete m_pt;
 }

private:
 CSingletonBase(const CSingletonBase& sig)
 {
 }

 CSingletonBase& operator = (const CSingletonBase& sig)
 {
 }

private:
 static T * m_pt;
};

template
T* CSingletonBase::m_pt = NULL;

template
class CSingletonEx : private CSingletonBase
{
public:
 CSingletonEx()
 {
 }

 virtual ~CSingletonEx()
 { 
 }

public:
 virtual T* Instance(void)
 {
 return CSingletonBase::Create();
 }

 virtual void Release(void)
 {
 CSingletonBase::Free();
 }

private:
 CSingletonEx(const CSingletonEx& sig)
 {
 }

 CSingletonEx& operator = (const CSingletonEx& sig)
 {
 }
};

#endif //SINGLETONEX__H__


////////////////////////////////
//测试类
//Doc.h

#ifndef CDOC__H__
#define CDOC__H__

class CDoc //测试类
{
public:
 CDoc(const std::string name = "NoName"):m_name(name){}
 virtual ~CDoc(){}

public:
 inline
 std::string Name()
 {
 return m_name;
 }

 inline
 void SetName(const std::string& name)
 {
 m_name=name;
 }

protected:
 std::string m_name;
};

#endif //CDOC__H__

////////////////////////////////////
//测试文件
//main.cpp

#include
#include
#include "singletonex.h"
#include "doc.h"

void TestSingletonEx(void)
{
 CSingletonEx s;

 CDoc *pdoc = s.Instance();

 std::cout<Name()<<:endl>

 pdoc->SetName("pdoc change:  My SingletonEx");

 CDoc *p2 = s.Instance();

 std::cout<Name()<<:endl>

 p2->SetName("p2 change: SingletonEx ");

 std::cout<Name()<<:endl>}

void main(void)
{
 std::cout< TestSingletonEx();
}

//the end!!


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10752043/viewspace-992355/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10752043/viewspace-992355/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值