2018-04-11
单例模式
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return singleton;
}
}
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
class Singleton{
private volatile static Singleton singleton; // volatile用于避免java的无序写入问题
private Singleton(){}
public static Singleton getInstance(){
if(singleton == null){ // 提高效率,避免同步代码的执行
synchronized(Singleton.class){
if(singleton == null) // 检查对象是否为空,防止单例重复创建
singleton = new Singleton();
}
}
return singleton;
}
}