单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
实现:单例模式的实现分为饿汉式和懒汉式两种
相同点:都提供一个私有的构造方法
不同点:饿汉模式是在类被加载时就生成对象,懒汉模式是在第一次使用的时候才生成对象
- 饿汉模式
class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {};
public static Singleton getInstance () {
return singleton;
}
}
- 懒汉模式
线程不安全
class Singleton {
private static Singleton singleton = null ;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
线程安全 加锁版本
class Singleton {
private static Singleton singleton = null;
private Singleton() {
}
public synchronized static Singleton getIntance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
线程安全 双重加锁版本
lass Singleton {
private volatile static Singleton singleton = null;
private Singleton() {
}
public static Singleton getInstance() {
if (singleton == null) {
synchronized(Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}