单例设计模式保证类在内存中只存在一个对象。根据不同的策略,单例类的实现有以下几种方式。
1. 立即加载
在加载类的同时实例化对象,设计要点如下:
(1)私有化构造方法;
(2)声明并实例化本类对象(静态);
(3)提供公有静态方法获取对象。
Code 1
public class EagerSingleton {
private EagerSingleton() {
// Initiate
}
// Other private constructors
private static EagerSingleton instance = new EagerSingleton();
public static EagerSingleton getInstance() {
return instance;
}
// Other methods
}
当成员不可变时,也可直接暴露给外部使用,简化如下:
Code 2
public class EagerSingleton {
private EagerSingleton() {
// Initiate
}
// Other private constructors
public static final EagerSingleton instance = new EagerSingleton();
// Other methods
}
2. 延迟加载(懒加载)
对象第一次使用时实例化,设计要点如下:
(1)私有化构造方法;
(2)声明本类的静态引用;
(3)提供公有静态方法获取对象,第一次获取时实例化。
Code 3
public class LazySingleton {
private LazySingleton() {
// Initiate
}
// Other private constructors
private static LazySingleton instance = null;
public static LazySingleton getInstance() {
if (instance == null)
instance = new LazySingleton();
return instance;
}
// Other methods
}
上述实现方式具有线程安全问题,当多个线程同时调用getInstance方法时,可能会创建多个实例。以下采用同步的方式解决线程安全问题:
Code 4
public class LazySingleton {
private LazySingleton() {
// Initiate
}
// Other private constructors
private static volatile LazySingleton instance = null;
public static LazySingleton getInstance() {
synchronized(LazySingleton.class) {
if (instance == null)
instance = new LazySingleton();
}
return instance;
}
// Other methods
}
Code 4 中的volatile关键字有两个作用:
(1)保证线程可见性:一个线程对volatile变量的修改会立即由工作内存(线程独享)写回主内存(线程共享),volatile使变量的修改可以及时反映到其他线程中;
(2)禁止指令重排序:由于编译器的优化,代码的实际执行顺序与编写顺序可能不一致。volatile关键字可禁止这种优化(JDK 1.5之后)。
Code 4 可以解决线程安全问题,但执行效率很低。因为实例化仅在第一次调用时执行,而每次获取实例时均要同步,线程排队导致效率降低。以下采用双重检查的方式避免线程排队:
Code 5
public class LazySingleton {
private LazySingleton() {
// Initiate
}
// Other private constructors
private static volatile LazySingleton instance;
public static LazySingleton getInstance() {
if (instance == null) {
synchronized(LazySingleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
// Other methods
}
上述实现略显繁琐,但可兼顾效率与安全(要求JDK版本至少为1.5)。
3. 枚举方式
枚举实现单例类最为简单,可以保证线程安全,同时可以防止通过反射调用私有方法。
Code 6
public enum EnumSingleton {
INSTANCE;
// Other codes
}
由于枚举类占用内存较多,移动开发不建议使用。
4. 静态内部类方式
因为静态内部类只会加载一次,并且仅在第一次访问时才加载,所以能够实现延迟加载,同时保证线程安全。
Code 7
public class StaticInnerClassSingleton {
private StaticInnerClassSingleton() {
// Initiate
}
// Other private constructors
public static StaticInnerClassSingleton getInstance() {
return StaticInnerClass.instance;
}
// Other methods
private static class StaticInnerClass {
// 外部类可以直接访问内部类的私有成员
private static StaticInnnerClassSingleton instance = new StaticInnerClassSingleton();
}
}
总结:单例类最常见的实现方式是立即加载和延迟加载,采用延迟加载时要注意线程安全问题。枚举可以简化实现,但占用资源相对较多。