定义
单例模式确保一个类只有一个实例, 并提供一个全局访问点
案例
实现单例模式只需要 私有的构造器, 一个静态方法和一个静态变量
BaseSingleton延迟加载, 存在线程安全问题
public class BaseSingleton {
private static BaseSingleton instanse;
private BaseSingleton() {
}
public static BaseSingleton getInstance() {
if (instanse == null) {
instanse = new BaseSingleton();
}
return instanse;
}
}
解决一: 通过饿汉式, 一开始就初始化
public class HungrySingleton {
private static HungrySingleton instance = new HungrySingleton();
private HungrySingleton() {
}
public HungrySingleton getInstance() {
return instance;
}
}
解决二
SyncSingleton加synchronized关键字
问题: 每次经过getInstance方法都会有同步的性能损耗, 实际只需要在第一次instance为null的时候保证只创建一次就行了
public class SyncSingleton {
private static SyncSingleton instance;
private SyncSingleton() {
}
public synchronized SyncSingleton getInstance() {
if (instance == null) {
instance = new SyncSingleton();
}
return instance;
}
}
解决三
DoubleCheckLockSingleton利用volatile和synchronized双重检查锁, 这样性能上损耗最低, 又是延迟加载线程安全的
public class DoubleCheckLockSingleton {
private volatile static DoubleCheckLockSingleton instance;
private DoubleCheckLockSingleton() {
}
public DoubleCheckLockSingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckLockSingleton.class) {
if (instance == null) {
instance = new DoubleCheckLockSingleton();
}
}
}
return instance;
}
}