单例模式: 保证一个类只有一个实例。
懒汉式单例:
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
双重锁定:
public class MultiThreadSingleton {
private static MultiThreadSingleton instance = null;
private static Object lock = new Object(); // 锁旗标
private MultiThreadSingleton() {
}
public static MultiThreadSingleton getInstance() {
if (instance == null) {
synchronized (lock) {
if (instance == null) {
instance = new MultiThreadSingleton();
}
}
}
return instance;
}
}
// 不用让线程每次都加锁,而只是在实例未被创建的时候再加锁处理,同时保证多线程的安全,这种做法叫双重锁定.
饿汉式单例:
public class HungrySingleton {
private static HungrySingleton instance = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return instance;
}
}
饿汉式单例:静态初始化,即类一加载就实例化对象,所以要提前占用系统资源。
懒汉式单例:面临多线程访问的安全性问题,需要做双重锁定才能保证安全,但性能会受一定影响。