单例模式

2018-01-22  本文已影响3人  倾倒的吞天壶
public class Singleton {  
    //不使用也会实例化, 比较浪费资源
    private static Singleton sInstance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return sInstance;  
    }  
}
public class Singleton {  
    private static Singleton sInstance = null;  
    private Singleton (){}  
  
    //使用时才会实例化, 但是每次都会同步, 造成不必要的同步浪费
    public static synchronized Singleton getInstance() {  
    if (sInstance == null) {  
        sInstance = new Singleton();  
    }  
    return sInstance;  
    }  
} 
public class Singleton {  
    //加入volatile关键字, 避免DCL失效问题
    private volatile static Singleton sInstance = null;  
    private Singleton (){}  
    public static Singleton getInstance() {  
    if (sInstance == null) {  
        synchronized (Singleton.class) {  
        if (sInstance == null) {  
            sInstance = new Singleton();  
        }  
        }  
    }  
    return sInstance;  
    }  
} 
//比较完美的写法, 但是会有反序列化失效问题
public class Singleton {  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  

    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
}  
//避免了上述方法反序列看化时产生新的对象
public enum Singleton {  
    INSTANCE;  
    public void doMethod() {  
    }  
} 

//使用方法
Singleton s = Singleton.INSTANCE;
s.doMethod();
上一篇 下一篇

猜你喜欢

热点阅读