设计模式

设计模式-单例

2021-03-28  本文已影响0人  漆先生

参考链接:https://www.runoob.com/design-pattern/singleton-pattern.html

一、单例模式

单例模式属于创建型模式。一个单一的类,创建自己的对象,同时确保只有单个对象被创建。给外部提供了一种访问其唯一的对象的方法,不再需要实例化该类的对象。

二、单例模式的常见实现形式

1.懒汉式,线程不安全

public class Singleton {
    private static Singleton instance = null;

    private Singleton() {

    }

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

2.懒汉式,线程安全

public class Singleton {
    private static Singleton instance = null;

    private Singleton() {

    }

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

3.饿汉式,线程安全

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

    private Singleton() {

    }

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

4.双检锁

public class Singleton {
    private volatile static Singleton instance = null;

    private Singleton() {

    }

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

5.静态内部类

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){}

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

6.枚举

public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  

    }  
}

三、总结

不建议使用懒汉式,建议使用饿汉方式。只有在要明确实现 lazy loading 效果时,才会使用静态内部类。如果涉及到反序列化创建对象时,可以尝试使用枚举方式。如果有其他特殊的需求,可以考虑使用双检锁方式。
延迟加载:静态内部类>双检索
非延迟加载:枚举>饿汉式

上一篇 下一篇

猜你喜欢

热点阅读