java设计模式之单例

public class Singleton {

    private static Singleton uniqueInatance;

    private Singleton() {

    }

    /**
     * 经典方式,多线程环境下不能保证单例,懒加载模式
     *
     * @return
     */
    public static Singleton getInstance() {
        if (uniqueInatance == null) {
            uniqueInatance = new Singleton();
        }

        return uniqueInatance;
    }


    /**
     * 1.急切模式,能保证单例,一开始就创建实例
     */
    private static Singleton uniqueInatance1 = new Singleton();

    public static Singleton getUniqueInatance1() {
        return uniqueInatance1;
    }

    /**
     * 2.同步方式,能保证单例,但对性能影响比较大
     */
    private static Singleton uniqueInatance2;

    public static synchronized Singleton getUniqueInatance2() {
        if (uniqueInatance2 == null) {
            uniqueInatance2 = new Singleton();
        }
        return uniqueInatance2;
    }

    /**
     * 3.双重检查模式,能保证单例,需要时创建对象,对性能影响可以忽略不计
     */
    private volatile static  Singleton uniqueInatance3;

    public static synchronized Singleton getUniqueInatance3() {
        if (uniqueInatance3 == null) {
            synchronized (Singleton.class){
                if (uniqueInatance3==null){
                    uniqueInatance3=new Singleton();
                }
            }
        }
        return uniqueInatance3;
    }
}

你可能感兴趣的:(java设计模式之单例)