回覆列表
  • 1 # 此圖我發朋友圈

    單例模式大致有五種寫法,分別為懶漢,惡漢,靜態內部類,列舉和雙重校驗鎖。

    1、懶漢寫法,常用寫法

    class LazySingleton{ private static LazySingleton singleton; private LazySingleton(){ } public static LazySingleton getInstance(){ if(singleton==null){ singleton=new LazySingleton(); } return singleton; } }

    2、惡漢寫法,缺點是沒有達到lazy loading的效果

    class HungrySingleton{ private static HungrySingleton singleton=new HungrySingleton(); private HungrySingleton(){} public static HungrySingleton getInstance(){ return singleton; }}

    3、靜態內部類,優點:載入時不會初始化靜態變數INSTANCE,因為沒有主動使用,達到Lazy loading

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

    4、列舉,優點:不僅能避免多執行緒同步問題,而且還能防止反序列化重新建立新的物件

    enum EnumSingleton{ INSTANCE; public void doSomeThing(){ }}

    5、雙重校驗鎖,在當前的記憶體模型中無效

    class LockSingleton{ private volatile static LockSingleton singleton; private LockSingleton(){} public static LockSingleton getInstance(){ if(singleton==null){ synchronized(LockSingleton.class){ if(singleton==null){ singleton=new LockSingleton(); } } } return singleton; }}

  • 中秋節和大豐收的關聯?
  • 有時候感覺自己活在夢中,是怎麼回事?