本文为笔者学习《Head First设计模式》的笔记,并加入笔者自己的理解和归纳总结
单例模式确保一个类只有一个实例,并提供一个全局访问点。
结构图
饿汉模式
public class Singleton {
private static Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
懒汉模式
public class Singleton {
private static volatile Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
静态内部类
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHandler.INSTANCE;
}
private static class SingletonHandler {
private static Singleton INSTANCE = new Singleton();
}
}
枚举
public class Singleton {
public enum SingletonHandler {
handler;
private Singleton singleton;
private SingletonHandler() {
singleton = new Singleton();
}
public Singleton getSingleton() {
return singleton;
}
}
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHandler.handler.getSingleton();
}
}
static代码块
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {
}
static {
INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return INSTANCE;
}
}
序列化
将Singleton实现序列化,需要添加implement Serializable
,并提供readResolve
方法。
private Object readResolve() {
return INSTANCE;
}
相关文章
Java 设计模式