标签:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class SingletonClass{ private static SingletonClass instance=null; public static SingletonClass getInstance(){ if(instance==null){ synchronized(SingletonClass.class){ if(instance==null){ instance=new SingletonClass(); } } } return instance; } private SingletonClass(){}} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class SingletonClass{ private static SingletonClass instance=null; public static synchronized SingletonClass getInstance() { if(instance==null) { instance=new SingletonClass(); } return instance; } private SingletonClass(){ }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//对第一行static的一些解释// java允许我们在一个类里面定义静态类。比如内部类(nested class)。//把nested class封闭起来的类叫外部类。//在java中,我们不能用static修饰顶级类(top level class)。//只有内部类可以为static。public class Singleton{ //在自己内部定义自己的一个实例,只供内部调用 private static final Singleton instance = new Singleton(); private Singleton(){ //do something } //这里提供了一个供外部访问本class的静态方法,可以直接访问 public static Singleton getInstance(){ return instance; }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
public class Singleton{ private static Singleton instance=null; private Singleton(){ //do something } public static Singleton getInstance(){ if(instance==null){ synchronized(Singleton.class){ if(null==instance){ instance=new Singleton(); } } } return instance; }}//这个模式将同步内容下方到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次才同步,创建了以后就没必要了。 |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
var Singleton=(function(){var instantiated;function init(){/*这里定义单例代码*/return{publicMethod:function(){console.log(‘helloworld‘);},publicProperty:‘test‘};}return{getInstance:function(){if(!instantiated){instantiated=init();}return instantiated;}};})();/*调用公有的方法来获取实例:*/Singleton.getInstance().publicMethod(); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class test { private static $_instance;//保存类实例的私有静态成员变量 //定义一个私有的构造函数,确保单例类不能通过new关键字实例化,只能被其自身实例化 private final function __construct() { echo ‘test __construct‘; } //定义私有的__clone()方法,确保单例类不能被复制或克隆 private function __clone() {} public static function getInstance() { //检测类是否被实例化 if ( ! (self::$_instance instanceof self) ) { self::$_instance = new test(); } return self::$_instance; }}//调用单例类test::getInstance(); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class CSingleton{private: CSingleton() //构造函数是私有的 { }public: static CSingleton * GetInstance() { static CSingleton *m_pInstance; if(m_pInstance == NULL) //判断是否第一次调用 m_pInstance = new CSingleton(); return m_pInstance; }}; |
标签:
原文地址:http://www.cnblogs.com/yg6405816/p/5518375.html