设计模式之单例模式

设计模式

单例模式

懒汉模式

class Person{
    /**
     * 单例模式设计
     */

    private String name;
    private int age;
    // 类字段

    private static Person person = null;
    // 定义一个私有变量以提供唯一实例

    private Person(){
    }
    // 私有化构造方法

    /**
     * 由于可能会有多线程访问,所以要锁
     * @return Person的唯一实例
     */
    public static synchronized Person getInstance(){
        if (person == null){
            person = new Person();
        }

        return person;
    }

    /**
     * 换个锁的位置保证效率
     * @return person的唯一实例
     */
    public static Person getInstance2(){
        if (person == null){
            synchronized (Person.class){
                if (person == null) {
                    person = new Person();
                }
            }
        }
        return person;
    }
}

饿汉模式

class Student{
    private static final Student STUDENT = new Student();
    // 预实例化变量保存起来

    private Student() {

    }
    // 私有化构造方法

    /**
     * 直接返回,只读不需要考虑锁的问你
     * @return Student的唯一实例
     */
    public static Student getInstance(){
        return STUDENT;
    }

}

总结

  1. 懒汉模式更节省内存,但是反之需要锁结构,会影响第一次访问时的效率
原文地址:https://www.cnblogs.com/rainful/p/15022071.html