美文网首页
Head First 设计模式(5)单例模式

Head First 设计模式(5)单例模式

作者: kaiker | 来源:发表于2021-07-13 20:31 被阅读0次

1、本章的例子——巧克力工厂

巧克力工厂例子
  • 如果有多个实例操控锅炉,可能造成严重的问题。尝试使用单例提供唯一的对象进行访问。
  • 另外,如果存在多线程,可能使用非同步的单例也不能满足需求。
多线程操纵锅炉

2、单例模式

确保一个类只有一个实例,并提供一个全局访问点。

单例类图 一个经典的单例
  • 私有的构造器
  • 静态的对象
  • 静态方法获取这个对象

几种同步的单例模式

public class Singleton {
  private static Singleton uniqueInstance;
  
  private Singleton() {}

  // 同步会有一些开销
  public static synchronized Singleton getInstance() {
    if (uniqueInstance == null) {
      uniqueInstance = new Singleton();
    }
    return uniqueInstance;
  }
}

public class Singleton {
  // 最开始就创建好
  private static Singleton uniqueInstance = new Singleton();
  private Singleton() {}
  public static Singleton getInstance() {
    return uniqueInstance;
  }
}

public class Singleton {
  private volatile static Singleton uniqueInstance;
  private Singleton();
  public static Singleton getInstance {
    if (uniqueInstance == null) {
      synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton();  
        }  
    }
  }
}
双重加锁单例

相关文章

网友评论

      本文标题:Head First 设计模式(5)单例模式

      本文链接:https://www.haomeiwen.com/subject/yrikpltx.html