首页 > 代码库 > Singleton 模式 Java,c++实现

Singleton 模式 Java,c++实现

 对于某些类,我们需要保证系统中只能有一个实例,这种类的设计用到singleton模式模式。

 

单线程的singleton模式是 straightforward的,下面给出Java和C++11的线程安全singleton实现

 

Java:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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++:

?
1
2
3
4
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.