1. 简介
单件模式(Singleton)也叫单例模式,是一种创建型模式。它确保一个类只有一个实例,并提供全局访问。
2. UML类图
Singleton中uniqueInstance类变量持有唯一的单件实例,getInstance()是静态方法,可以通过类名在任何需要的地方使用它,与访问全局变量一样,但是可以延迟实例化。
3. 实例
饿汉式:类加载就初始化实例,达到了线程安全的效果,但是在不需要的时候就实例化可能会造成资源浪费。
public class Singleton {
private static Singleton instance = new Singleton();
private Singletone() {}
public static Singleton getInstance() {
return instance;
}
}
懒汉式:在需要的时候再初始化实例,线程不安全
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懒汉式(同步方法):在需要的时候再初始化实例,线程安全,效率低下
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
双重检查:在需要的时候再初始化实例,线程安全,效率较高
public class Singleton {
private static Singleton instance;
private Singleton() {};
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}