Java設計模式---單例模式

單例模式的幾種實現方法,具體以下:java

懶漢模式

public class Singleton{
    private static Singleton instance;

    private Singleton(){
    }

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

優勢緩存

  • 能夠延遲加載安全

缺點多線程

  • 多線程不安全spa

餓漢模式

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

    private Singleton(){}

    public static Singleton getInstance(){
        return instance;
    }
}

優勢.net

  • 多線程安全線程

缺點code

  • 加載類時就初始化完成,沒法延時加載內存

雙重檢查

public class Singleton {

    private static Singleton instance ;

    private Singleton(){}

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

優勢get

  • 多線程安全

  • 延遲加載

缺點

  • 同步耗時

靜態內部類

public class Singleton {

    private Singleton(){}

    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static Singleton instance = new Singleton();
    }
}

優勢

  • 多線程安全

  • 延遲加載

  • 耗時短(與雙重檢查相比)

用緩存實現

public class Singleton {

    private static final String KEY = "instance";

    private static Map<String, Singleton> map = new HashMap<>();

    private Singleton(){}

    public static Singleton getInstance(){
        Singleton singleton ;
        if (map.get(KEY) == null){
            singleton = new Singleton();
            map.put(KEY, singleton);
        } else {
            singleton = map.get(KEY);
        }
        return singleton;
    }
}

優勢

  • 線程安全

缺點

  • 佔用內存較大

枚舉模式

public enum Singleton {

    instance;

    public void operate(){}
}

優勢

  • 簡潔

缺點

  • 佔用內存大(Android官方不推薦使用枚舉)

更多文章請移步個人博客:DevWiki Bolg

相關文章
相關標籤/搜索