1. 程式人生 > >java單例模式實現方式總結

java單例模式實現方式總結

public class SingletonObject1 {
    private static final SingletonObject1 singletonObject1 = new SingletonObject1();

    private SingletonObject1(){}

    public static SingletonObject1 getInstance() {
        return singletonObject1;
    }
}

方式二:

public class SingletonObject5 {
    private static  volatile SingletonObject5 singletonObject5 = null;

    private SingletonObject5(){}

    public SingletonObject5 getInstance() {
        if(singletonObject5 == null) {
            synchronized (SingletonObject5.class) {
                if(singletonObject5 == null) {
                    singletonObject5 = new SingletonObject5();
                }
            }
        }
        return singletonObject5;
    }
}

方式三:

public class SingletonObject6 {

    private SingletonObject6(){}

    private static class InstanceHolder {
        private final static SingletonObject6 instance = new SingletonObject6();
    }

    public static SingletonObject6 getInstance() {
        return InstanceHolder.instance;
    }
}

方式四:

public class SingletonObject7 {

    private SingletonObject7(){}

    private enum Singleton{
        INSTANCE;
        private final SingletonObject7 instance;

        Singleton() {
            instance = new SingletonObject7();
        }
        public SingletonObject7 getInstance() {
            return instance;
        }
    }

    public static SingletonObject7 getInstance() {
        return Singleton.INSTANCE.getInstance();
    }
}

總結:一般情況下,對記憶體佔用沒有過多考慮可以選擇方式1,可以直接在記憶體中先生成單例物件。

後續三種方案都是採用懶載入的例項生成,方式二中使用鎖、volatile實現,頻繁使用還是有效能損耗。

更推薦方式3、4的實現方式,沒有使用鎖,同時實現了懶