首页 > 代码库 > 设计模式(1)单例模式

设计模式(1)单例模式

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

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

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

 

?
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