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

本文介绍了C++中Singleton设计模式的一种模板实现方式,包括模板类`CSingletonBase`和`CSingletonEx`的定义及用法。通过示例展示了如何创建和使用Singleton实例,并提供了测试类`CDoc`来验证Singleton模式的功能。

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

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

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

 在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 T>
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<class T>
T* CSingletonBase<T>::m_pt = NULL;

template<class T>
class CSingletonEx : private CSingletonBase<T>
{
public:
 CSingletonEx()
 {
 }

 virtual ~CSingletonEx()
 {  
 }

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

 virtual void Release(void)
 {
  CSingletonBase<T>::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<iostream>
#include<string>
#include "singletonex.h"
#include "doc.h"

void TestSingletonEx(void)
{
 CSingletonEx<CDoc> s;

 CDoc *pdoc = s.Instance();

 std::cout<<pdoc->Name()<<std::endl;

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

 CDoc *p2 = s.Instance();

 std::cout<<p2->Name()<<std::endl;

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

 std::cout<<pdoc->Name()<<std::endl;
}

void main(void)
{
 std::cout<<"******** Test SingletonEx Start ******** "<<std::endl;
 TestSingletonEx();
}

//the end!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值