【设计模式】单例模式

你离开我真会死。 提交于 2020-02-15 10:14:17

饱汉模式

//lazy
class LazyPerson {
    private static volatile LazyPerson person;

    private LazyPerson(){}

    public static LazyPerson getSingleton() {
        if (person == null) {
            synchronized (LazyPerson.class) {
                if (person ==null) {
                    person = new LazyPerson();
                }
            }
        }
        return person;
    }
}

饿汉模式

//hungry
class HungryPerson {
    private HungryPerson(){}

    private static HungryPerson hungryPerson = new HungryPerson();

    public static HungryPerson getHungryPerson() {
        return hungryPerson;
    }
}

饱汉模式利用Java的类加载机制保证线程安全,而饿汉模式则需要使用volatile和synchronized以及双重检查机制来保证线程安全。

测试代码

public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        HungryPerson hungryPerson = HungryPerson.getHungryPerson();
        System.out.println(hungryPerson);
        HungryPerson hungryPerson1 = HungryPerson.getHungryPerson();
        System.out.println(hungryPerson1);
        System.out.println(hungryPerson == hungryPerson1);

        /*//lazy start
        new Thread(()-> {
            Person person = Person.getSingleton();
            System.out.println(person);
        }).start();

        new Thread(() -> {
            Person person = Person.getSingleton();
            System.out.println(person);
        }).start();
        // lazy end*/
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!