HelloWorld开发者社区

www.helloworld.net - 开发者专属的技术社区

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  78 随笔 :: 0 文章 :: 13 评论 :: 50061 阅读

程序中有时候需要保存全局的数据,比如程序的配置文件,需要随时检索的.比如程序中有些变量需要全局保存全局用,这时候我们不想用一个全局变量来保存

这时候,可以使用单例模式,从名称可以看出,单例模式就是类的实例全局只创建一个.怎么样才能保存只创建一个实例呢?

我们可以设置标识位,创建过的就不再创建了.下面是单例的简单实现

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
template<class T>
  class Singleton
  {
  public:
      static T* GetInstance()
      {
          static Mutex mutex;
          if(!ms_instance)
          {
              Locker locker(mutex);
              if (!ms_instance)
              {
                  ms_instance = new T;
              }
          }
 
          return ms_instance;
      }
 
      static void SetInstance(T* pInst)
      {
          ms_instance = pInst;
      }
 
      static void DeleteInstance()
      {
          if (ms_instance)
          {
              delete ms_instance;
              ms_instance = NULL;
          }
      }
  private:
      class Garbo
      {
      public:
          ~Garbo()
          {
              if( Singleton::ms_instance )
              {
 
                  delete ms_instance;
                  ms_instance = NULL;
              }
          }
      };
      static Garbo garbo;
  protected:
      Singleton() {}
      ~Singleton() {}
 
      Singleton(const Singleton&) {}
      Singleton& operator=(const Singleton&) {}
 
  private:
      static T*           ms_instance;
 
  };
 
  template<class T>
  T* Singleton<T>::ms_instance = 0;

  

 

用法:

class Test : public Singleton<Test>

{

//your code

}

 

Test::GetInstance()->your method

 

 

 

 

posted on   HelloWorld开发者社区  阅读(167)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示