單例模式的幾種寫法

實現方法一:

餓漢式

    public static class Singleton{
        private static Singleton instance = new Singleton();
        private Singleton(){}
        public static Singleton getInstance(){
            return instance;
        }
    }

實現方法二:

懶漢式

    public static class Singleton{
        private static Singleton instance;
        private Singleton(){};
        public static synchronized Singleton getInstance(){
            if(instance == null){
                instance = new Singleton();
            }
            return instance;
        }
    }

實現方法三

雙重檢驗加鎖

    public static class Singleton{
        private static volatile Singleton instance;
        private Singleton(){}
        public static Singleton getInstance(){
        //先檢查實例是否存在,如果不存在才進入下面的同步塊
            if(instance == null){
            //同步塊,線程安全的創建實例
                synchronized (Singleton.class){
                //再次檢查實例是否存在,如果不存在才真正的創建實例
                    if(instance == null){
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

實現方法四

靜態內部類

    public static class Singleton{

        private static class SingletonHolder{
            private static final Singleton instance = new Singleton();
        }
        private Singleton(){}
        public static Singleton getInstance(){
            return SingletonHolder.instance;
        }
    }

實現方法五

    public static class Singleton{
        private static class SingletonHolder{
            private static final Singleton instance = new Singleton();
        }
        private Singleton(){}
        public static Singleton getInstance(){
            return SingletonHolder.instance;
        }
    }

實現方法六

枚舉式,實現單例最推薦使用的實現方式
優點:1.線程安全 2.不會因爲序列化而產生新實例 3.防止反射攻擊

public enum Singleton {

    INSTANCE;

    private Singleton(){}

    public Singleton getInstance(){
        return INSTANCE;
    }
}

也可以修改一下構造方法,測試一下

public enum EmuTest {
    private final  int age;
    private final String name;
    INSTANCE("fonxian",22);
    //INSTANCE就相當於private static EmuTset instance = new EmuTest();
    private EmuTest(String name,int age){
        this.name = name;
        this.age = age;
    }

    public EmuTest getInstance(){
        return INSTANCE;
    }
}

測試

public class SingletonTest {
    public static void main(String[] args) {
        EmuTest et1 = EmuTest.INSTANCE.getInstance();
        EmuTest et2 = EmuTest.INSTANCE.getInstance();
        //返回的結果是true
        System.out.println(et1==et2);
    }
}
發佈了73 篇原創文章 · 獲贊 11 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章