Singleton 模式

收集了两篇文章有很多近似又有不同,认真地读完第一篇;

第二片有些不同,日后在细比较。


The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
A static variable which holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static method GetInstance as the means of accessing the instance. In all cases, the method could easily be converted to a property with only an accessor, with no impact on thread-safety or performance.

First version - not thread-safe

1)非线程安全的Singleton
public sealed class Singleton

      static Singleton instance=null; 
      Singleton() 
      { 
      }
      public static Singleton GetInstance() 
      {
            if (instance==null) 
            instance = new Singleton(); 
            return instance; 
      }
 }
 

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

2)简单的线程安全的Singleton, 用只读锁,但是每次需要一个新的实例都要锁,比较浪费时间
public sealed class Singleton

      static Singleton instance=null; 
      static readonly object padlock = new object(); 
      Singleton() 
      { 
      }
       public static Singleton GetInstance() 
      { 
            lock (padlock) 
            { 
                  if (instance==null) 
                  instance = new Singleton(); 
                  return instance;
             } 
      }
}
 

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

3)“双检测锁”的线程安全Singleton
public sealed class Singleton

      static Singleton instance=null; 
      static readonly object padlock = new object(); 
      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            if (instance==null) 
            { 
                  lock (padlock) 
                  {
                        if (instance==null) 
                        instance = new Singleton(); 
                  } 
            } 
            return instance;
      }
}
 

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model is going through a reworking for version 1.5, but double-check locking is anticipated to still be broken after this.
It almost certainly doesn't work in .NET either. Claims have been made that it does, but without any convincing evidence. Various people who are rather more trustworthy, however, such as Chris Brumme, have given convincing reasons why it doesn't. Given the other disadvantages, why take the risk? I believe it can be fixed by making the instance variable volatile, but that slows the pattern down more. (Of course, correct but slow is better than incorrect but broken, but when speed was one of the reasons for using this pattern in the first place, it looks even less attractive.) It can also be fixed using explicit memory barriers, but experts seem to find it hard to agree on just which memory barriers are required. I don't know about you, but when experts disagree about whether or not something should work, I try to avoid it entirely.
It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
It still doesn't perform as well as the later implementations.
 
Fourth version - not quite as lazy, but thread-safe without using locks

4)无锁的线程安全的Singleton(非懒惰的)
public sealed class Singleton

      static readonly Singleton instance=new Singleton(); 
      // Explicit static constructor to tell C# compiler
      // not to mark type as beforefieldinit 
      static Singleton() 
      { 
      } 
      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            return instance; 
      }
}
 

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

It's not as lazy as the other implementations. In particular, if you have static members other than GetInstance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the method entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a method in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

5)完全惰性的实例化
public sealed class Singleton

      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            return Nested.instance; 
      } 
      class Nested 
      {
            // Explicit static constructor to tell C# compiler 
            // not to mark type as beforefieldinit 
            static Nested() 
            { 
            }
             internal static readonly Singleton instance = new Singleton(); 
      }
}
 

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in GetInstance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness
In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. Conclusion
There are various different ways of implementing the singleton pattern in C#. The final two are generally best, as they are thread-safe, simple, and perform well. I would personally use the fourth implementation unless I had some other static members which really shouldn't trigger instantiation, simply because it's the simplest implementation, which means I'm more likely to get it right. The laziness of initialization can be chosen depending on the semantics of the class itself.

 

 

戏说Singleton模式

DragonCheng

GOF著作中对Singleton模式的描述为:保证一个class只有一个实体(Instance),并为它提供一个全局访问点(global access point)

从其描述来看,是非常简单的,但实现该模式却是复杂的。Singleton设计模式不存在一种所谓的“最佳”方案。需要根据当时的具体问题进行具体解决,下面将讲述在不同环境下的解决方案。

Singleton的详细解释,请大家看GOF的著作《设计模式》一书。俺比较懒,是不想抄了。J

1         Singleton创建

1.1      GOF Singleton

GOF著作中对Singleton模式的实现方式如下:

/*解一*/

class Singleton

{

public:

static Singleton *Instance(){                            //1

if( !m_pInstatnce) //2

m_pInstance = new Singleton;//3

return m_pInstance; //4

}

private:

static Singleton *m_pInstatnce;             //5

private:

Singleton();                                                         //6

Singleton(const Singleton&);                             //7

Singleton& operator=(const Singleton&);            //8

~Singleton();                                                       //9

}

Singleton *Singleton:m_pInstatnce = NULL; //10

 

在上面的解决方案中,我们只在需要调用时,才产生一个Singleton的对象。这样带来的好处是,如果该对象产生带来的结果很昂贵,但不经常用到时,是一种非常好的策略。但如果该Instance被频繁调用,那么就有人觉得Instance中的判断降低了效率(虽然只是一个判断语句^_^,那么我们就把第5条语句该为

static Singleton m_Instatnce;

如此一来,在Instatnce直接返回&m_Instance,而不用做任何判断,效率也高了。(是不是呢?)

这样修改后,我们将带来灾难性的后果:

1:首先有可能编译器这关就没法通过,说m_Instance该外部变量无法解决(visural C++6.0

error LNK2001: unresolved external symbol "private: static class Singleton  Singleton::m_Instance" (?m_Instance@Singleton@@0V1@A)

2:如果编译器这关通过了就没问题了么?答案是否定的。

第一是不管Instance是否用到,该静态变量对象在编译器编译时就产生了,即资源消耗是不可避免的;

第二是无法确保编译器一定先将m_Instance初始化。所以Instance的调用有可能传回一个尚没构造的Singleton对象。这也意味着你无法保证任何外部对象所使用的m_Instance是一个被正确初始化的对象。

1.2      Meyers Singleton

我们如何解决这个问题呢,实际上很简单。一种非常优雅的做法由Scott Meyers最先提出,故也称为Meyers Singleton。它依赖编译器的神奇技巧。即函数内的static对象只在该函数第一次执行时才初始化(请注意不是static常量)。

/*解二*/

class Singleton

{

public:

static Singleton *Instance(){                            //1

static Singleton sInstance; //2

return &sInstance; //3

}

private:

Singleton();                                                         //4

Singleton(const Singleton&);                             //5

Singleton& operator=(const Singleton&);            //6

~Singleton();                                                       //7

}

 

解二在Instance中定义了一个StaticSingleton对象,来解决Instance中初始化的问题,也很顺利的解决了定义Static成员对象带来的问题。

请注意,解二在VC6中不能编译通过,将有以下的错误:

error C2248: 'Singleton::~Singleton' : cannot access private member declared in class 'Singleton' e:/work/q/a.h(81) : see declaration of 'Singleton::~Singleton'

产生该问题的错误原因是什么呢(请仔细思考^_^)

原因在于在产生static Singleton对象后,编译器会自动产生一个销毁函数__DestroySingleton,然后调用atexit()注册,在程序退出时执行__DestroySingleton。但由于Singleton的析构函数是private,所以会产生访问错误。(应该在以后的编译器中修改了该BUG

1.3      Singleton改进

Instance传回引用(reference)。如果传回指针,调用端有可能讲它delete调。

1.4      Singleton注意之点

在上面的解法中,请注意对构造函数和析构函数的处理,有何好处(请自己理解,俺懒病又犯了L)。

2         多线程

在解一中,如果我们运行在多线程的环境中,该方案是完美的么,将会有什么后果呢?

后果就是会造成内存泄漏,并且有可能前后获取的Singleton对象不一样(原因请自己思考,后面有解答)。

为了解决这个问题,将解一的Instance改为如下:

Singleton& Singleton::Instance(){

Lock(m_mutex);            //含义为获取互斥量            //1

If( !m_pInstance ){                                          //2

m_pInstance = new Singleton; //3

}

UnLock(m_mutex);                                            //4

return *m_pInstance;                                     //5

}

此种方法将解决解一运行在多线程环境下内存泄漏的问题,但带来的结果是,当m_mutex被锁定时,其它试图锁定m_mutex的线程都将必须等等。并且每次执行锁操作其付出的代价极大,亦即是这种方案的解决办法并不吸引人。

那么我们将上面的代码改为如下方式:

Singleton& Singleton::Instance(){

If( !m_pInstance ){                                                      //1

Lock(m_mutex); //含义为获取互斥量 //2

m_pInstance = new Singleton; //3

UnLock(m_mutex); //4

}

return *m_pInstance;                                                 //5

}

这样修改的结果没有问题了么?NO!!!!该方案带来的结果同解一,原因也一样,都将造成内存泄漏。此时“双检测锁定”模式就粉墨登场了。

Doug SchmidtTim Harrison提出了“双检测锁定”(Double-Checked Locking)模式来解决multithread singletons问题。

Singleton& Singleton::Instance(){

If( !m_pInstance ){                                                      //1

Lock(m_mutex); //含义为获取互斥量 //2

If(!m_pInstance) //3

m_pInstance = new Singleton; //4

UnLock(m_mutex); //5

}

return *m_pInstance;                                                 //6

}

请看上面的第三句,这句话是不是具有化腐朽为神奇的力量啊 ^_^

上面的方案就完美了么。回答还是NO!!!(各位看官是否已经郁闷了啊,这不是玩我啊?请耐心点,听我细细到来^_^)

如果在RISC机器上编译器有可能将上面的代码优化,在锁定m_mutex前执行第3句。这是完全有可能的,因为第一句和第3句一样,根据代码优化原则是可以这样处理的。这样一来,我们引以为自豪的“双检测锁定”居然没有起作用( L)

怎么办?解决呗。怎么解决?简单,我们在m_pInstance前面加一个修饰符就可以了。什么修饰符呢?…….

 

àvolatile(简单吧,让我们J)

那么我们完整的解法如下:

/*解三*/

class Singleton

{

public:

static Singleton &Instance(){                            //1

if( !m_pInstatnce){ //2

Lock(m_mutex) //3

If( !m_pInstance ) //4

m_pInstance = new Singleton;//5

UnLock(m_mutex); //6

}

return *m_pInstance; //7

}

private:

static volatitle Singleton *m_pInstatnce;            //8

private:

Singleton();                                                         //9

Singleton(const Singleton&);                             //10

Singleton& operator=(const Singleton&);            //11

~Singleton();                                                       //12

}

Singleton *Singleton:m_pInstatnce = NULL; //13

3         Singleton销毁

在这里,我们就到了Singleton最简单也最复杂的地方了。

为什么说它简单?我们根本可以不理睬创建的对象m_pInstance的销毁啊。因为虽然我们一直没有将Singleton对象删除,但不会造成内存泄漏。为什么这样说呢?因为只有当你分配了累积行数据并丢失了对他的所有reference是,内存泄漏才发生。而对Singleton并不属于上面的情况,没有累积性的东东,而且直到结束我们还有它的引用。在现代操作系统中,当一个进程结束后,将自动将该进程所有内存空间完全释放。(可以参考《effective C++》条款10,里面讲述了内存泄漏)。

但有时泄漏还是存在的,那是什么呢?就是资源泄漏。比如说如果该Singleton对象管理的是网络连接,OS互斥量,进程通信的handles等等。这时我们就必须考虑到Singleton的销毁了。谈到销毁,那可是一个复杂的课题(两天三夜也说不完^_^  开玩笑的啦,大家轻松一下嘛)。

我们需要在恰当的地点,恰当的时机删除Singleton对象,并且还要在恰当的时机创建或者重新创建Singleton对象。

在我们的“解二”中,在程序结束时会自动调用Singleton的析构函数,那么也将自动释放所获取的资源。在大多数情况下,它都能够有效运作。那特殊情况是什么呢?

我们以KDLkeyboarddisplaylog)模型为例,其中K,D,L均使用Singleton模式。只要keyboard或者display出现异常,我们就必须调用log将其写入日志中,否则log对象不应该创建。对后面一条,我们的Singleton创建时就可以满足。

在前面我们已经说到,在产生一个对象时(非用new产生的对象),由编译器自动调用了atexit(__DestroyObject)函数来实现该对象的析构操作。而C++对象析构是LIFO进行的,即先产生的对象后摧毁。

如果在一般情况下调用了log对象,然后开始销毁对象。按照“后创建的先销毁”原则:log对象将被销毁,然后display对象开始销毁。此时display在销毁发现出现异常,于是调用log对象进行记录。但事实上,log对象已经被销毁,那么调用log对象将产生不可预期的后果,此问题我们称为Dead Reference。所以前面的解决方案不能解决目前我们遇到的问题。

Andrei Alexandrescu提出了解决方案,称为Phoenix Singleton(取自凤凰涅磐典故)

/*解四*/

class Singleton

{

public:

static Singleton &Instance(){                           

if( !m_pInstatnce){

Lock(m_mutex)

If( !m_pInstance ){

if(m_destroyed)

OnDeadReference();

else

Create();

}

UnLock(m_mutex);

}

return *m_pInstance;

}

private:

static volatitle Singleton *m_pInstatnce;

static bool m_destroyed;

private:

Singleton();                                                        

Singleton(const Singleton&);                            

Singleton& operator=(const Singleton&);    

~Singleton(){

m_pInstance = 0;

m_destroyed = true;

}

static void Create(){

static Singleton sInstance;

m_pInstanace = &sInstance;

}

static void OnDeadReference(){

Create();

new (m_pInstance) Singleton;

atexit(KillPhoenixSingleton);

m_destroyed = false;

}

void KillPhoenixSingleton(){

m_pInstance->~Singleton();

}

}

Singleton *Singleton:m_pInstatnce = NULL;

bool m_destroyed =false; 

请注意此处OnDeadReference()中所使用的new操作符的用法:是所谓的placement new操作,它并不分配内存,而是在某个地址上构造一个新对象。

这是解决Dead Reference方法之一。如果此时keyboard或者display对象也需要处理Dead Reference问题时,那么上面的OnDeadReference将被频繁调用,效率将会很低。即该问题为:需要提供一种解决方案,用于处理对象的建立过程可以不按照“先创建会销毁”的原则,而应该为其指定一个销毁顺序。

聪明的Andrei Alexandrescu提出了一个“带寿命的Singleton”解决方案。该方案的思想是:利用atexit()的特性;在每次创建一个对象后,将该对象放入到一个链表中(该链表是按照销毁顺序排训的),并同时调用atexit()注册一个销毁函数;该销毁函数从链表中获取最需要销毁的对象进行销毁。(懒病又犯了L。该模式的实现请各位看官自行实现,可以参考《C++设计新思维》一书,Andrei Alexandrescu)

 

各位看官,看完本篇后,是否觉得Singleton还简单啦J

===

自己的理解:当时允许某个类只有一个实例存在时,采用Singleton 设计模式。

 要记得考虑线程安全性和执行效率。


===

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值