设计模式-单例模式

单例模式分为饿汉式、懒汉式

饿汉式:类加载时直接创建实例,类加载时已经生成示例,所以线程安全

public class SingletonOne {

    //类加载时初始化示例
    private static SingletonOne instance = new SingletonOne();
    private SingletonOne(){};
    private static SingletonOne getInstance() {
        return instance;
    }

    public static void main(String[] args) {
        SingletonOne s1 = getInstance();
        SingletonOne s2 = getInstance();
        System.out.println(s1 == s2);//true
    }
}

懒汉式:用到实例的时候再创建,多线程场景下,创建出的实例可能不唯一,违反了单一实例原则

下方测试代码在多线程模式下,s1可能不等于s2

public class SingletonTwo {

    private static SingletonTwo instance = null;
    private SingletonTwo(){};
    //用到实例时再创建
    private static SingletonTwo getInstance() {
        if(instance == null) {
            instance = new SingletonTwo();
        }
        return instance;
    }

    public static void main(String[] args) {
        SingletonTwo s1 = getInstance();
        SingletonTwo s2 = getInstance();
        System.out.println(s1 == s2);//true
    }
}

你可能感兴趣的:(设计模式,单例模式)