对于某些类,我们需要保证系统中只能有一个实例,这种类的设计用到singleton模式模式。
单线程的singleton模式是 straightforward的,下面给出Java和C++11的线程安全singleton实现
Java:
public class Singleton { private static Singleton instance = null; private static Object mutex = new Object(); private Singleton() { } public static Singleton getInstance() { if(instance == null) { synchronized(mutex) { if(instance == null) instance = new Singleton(); } } return instance; } }
C++:
static Singleton& get(){ static Singleton instance; return instance; }
C++11 remove the need for manual locking. Concurrent execution shall wait if a static local variable is already being initialized.