[Design Pattern]:Singleton

    技术2022-05-11  159

    使用单态模式的一个必要条件是:在系统中要求一个类只有一个实例时才使用,它必须自行创造这个实例,必须自行向系统提供这个实例。好处在于节省系统资源,保证系统访问的一致性。

    1 – Eager Singleton:

    class EagerSingleton{    private EagerSingleton(){}//私有的构造函数,保证外部不可访问    private static EagerSingleton instance = new EagerSingleton();    public static EagerSingleton getInstance(){        return instance;    }}

    public class Test {    public static void main(String args[]){        EagerSingleton e = EagerSingleton.getInstance();    }}

    该类加载时,静态变量instance被初始化,此时调用了它的私有的构造方法, 单一的实例就被创建了,为了保证只有一个实例,必须把此类的构造方法设为私有。

    2 – Lazy Singleton:

    class LazySingleton{    private static LazySingleton instance = null;    private LazySingleton(){}//私有的构造函数,保证外部不可访问    public synchronized static LazySingleton getInstance(){        if (instance == null){            instance = new LazySingleton();        }        return instance;    }}

    public class Test {    public static void main(String args[]){        LazySingleton e = LazySingleton.getInstance();    }}

    LazySingleton只有在第一次调用时才生成LazySingleton实例,提高了效率, synchronized保证了系统只有一个实例存在,因为如果两个类同时第一次访问这个类时, 如果没有同步的保证,那么就可能生成两个不同的实例。

    最新回复(0)