首页 > 编程语言 > 详细

Singleton 模式 Java,c++实现

时间:2014-05-26 11:02:45      阅读:301      评论:0      收藏:0      [点我收藏+]

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

Singleton 模式 Java,c++实现

原文:http://www.cnblogs.com/zhouzhuo/p/3747169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!