枚举类实现单例模式
实现单例模式时候,要思考四个问题:
- 是否线程安全
- 多线程安全了,效率是否能接受
- 是否可以延迟加载
- 是否支持序列化
请看下面一张图:
枚举实现单例模式如下:简洁优雅
public enum Singleton 0 {
INSTANCE;
int anInt;
public int getAnInt() {
return anInt;
}
public void setAnInt( int anInt ) {
this.anInt = anInt;
}
public void dosomethings( ) {
System.out.println("枚举类实现单例");
}
}
恶汉式单例模式如下:
public class Singleton 1{
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
饱汉式单例模式
public class Singleton2 {
private static Singleton2 singleton;
private Singleton2(){
}
public static synchronized Singleton2 getInstance(){
if(singleton == null)
singleton = new Singleton2();
return singleton;
}
双重锁模式(DCL):
public class Singleton3 {
private static Singleton3 singleton;
private Singleton3(){
}
public static Singleton3 getInstance(){
if(singleton == null){
synchronized(Singleton3.class){
if(singleton == null){
singleton = new Singleton3();
}
}
}
return singleton;
}