Singleton 模式 Java,c++实现

时间:2014-05-26 11:03:20   收藏:0   阅读:182

 对于某些类,我们需要保证系统中只能有一个实例,这种类的设计用到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.

Singleton 模式 Java,c++实现,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!