设计模式学习 - 单例模式

学习、梳理设计模式。

单例模式

单例模式分为饿汉模式和懒汉模式。

饿汉模式

  1. 私有化构造函数
  2. 创建私有实例
  3. 提供公开的获取实例的方法

    public class Person {
    
    private static Person instance = new Person();
    
    private Person() {
    
    }
    
    public static Person getInstance() {
        return instance;
    }
    
    }

懒汉模式

  1. 私有化构造函数
  2. 声明私有实例
  3. 提供公开的获取实例的方法(获取时为空则进行创建)

    public class Person {
    
    private static Person instace;
    
    private Person() {
    
    }
    
    public static Person getInstance() {
    
        if (instace == null) {
            return new Person();
        }
    
        return instace;
    }
    }

总结

两种模式都需要先私有化构造函数以禁止直接new操作来创建实例,不然就失去了单例的意义。

饿汉与懒汉在实例化的时间节点上,不同的地方在于一个是类加载时就实例化,一个是到用到时再去实例化,这也是其区别,前者在类加载时慢但获取时快,后者在类加载时快但获取时慢。同时,因为懒汉模式是在用到时才去实例化,也是其线程不安全的地方。

这个时候可以用下面的方式来规避

   public static Person getInstance() {

        if (instace == null) {
            synchronized (Person.class) {
                if (instace == null) {
                    return new Person();
                }
            }
        }

        return instace;
    }