singleton_java

Singleton

Java 线程安全单例的实现

Simplest

1
2
3
4
5
6
7
8
9
10
public final class EagerSingleton 
{

private static EagerSingleton singObj = new EagerSingleton();
private EagerSingleton(){
}

public static EagerSingleton getSingleInstance(){
return singObj;
}
}

Lazy-load

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public final class DoubleCheckedSingleton 
{

private static DoubleCheckedSingleton singObj = null;

private DoubleCheckedSingleton(){
}

public static DoubleCheckedSingleton getSingleInstance(){
if(null == singObj ) {
synchronized(DoubleCheckedSingleton.class){
if(null == singObj)
singObj = new DoubleCheckedSingleton();
}
}
return singObj;
}
}

Initialization on Demand Holder

1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton   
{

private static class SingletonHolder
{

public final static Singleton instance = new Singleton();
}

public static Singleton getInstance()
{

return SingletonHolder.instance;
}
}

参考于这里


index