定义:确保一个类只有一个实例,并提供全局访问点。
饿汉模式(公开域,存在内存消耗小问题)
public class Singleton1 implements Serializable {
public static final Singleton1 SINGLETON = new Singleton1 ( ) ;
private Singleton1 ( ) { }
public Object readResolve ( ) {
return SINGLETON;
}
}
饿汉模式(私有域,提供公开方法,存在内存消耗的小问题)
public class Singleton2 implements Serializable {
private static final Singleton2 SINGLETON = new Singleton2 ( ) ;
private Singleton2 ( ) { }
public static Singleton2 getUniqueInstance ( ) {
return SINGLETON;
}
public Object readResolve ( ) {
return SINGLETON;
}
}
懒汉模式(锁方法,存在性能问题)
public class Singleton3 implements Serializable {
private static Singleton3 SINGLETON;
private Singleton3 ( ) { }
public static synchronized Singleton3 getUniqueInstance ( ) {
if ( SINGLETON == null) {
SINGLETON = new Singleton3 ( ) ;
}
return SINGLETON;
}
public Object readResolve ( ) {
return SINGLETON;
}
}
懒汉模式(双重检测锁,某段时间内被认为最严谨的单例实现方法)
public class Singleton4 implements Serializable {
private static volatile Singleton4 SINGLETON;
private Singleton4 ( ) { }
public static Singleton4 getUniqueInstance ( ) {
if ( SINGLETON == null) {
synchronized ( Singleton4. class ) {
if ( SINGLETON == null) {
SINGLETON = new Singleton4 ( ) ;
}
}
}
return SINGLETON;
}
public Object readResolve ( ) {
return SINGLETON;
}
}
内部类
public class Singleton5 implements Serializable {
private Singleton5 ( ) { }
private static class SingletonHolder {
private static final Singleton5 instance= new Singleton5 ( ) ;
}
public static Singleton5 getInstance ( ) {
return SingletonHolder. instance;
}
public Object readResolve ( ) {
return SingletonHolder. instance;
}
}
枚举类单例模式(Java创始人书写,jdk1.5之后推荐)
public enum Singleton {
INSTANCE;
}