Singleton: Intent
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
Singleton 是一种创建性设计模式,它允许您确保一个类只有一个实例,同时提供对此实例的全局访问点。
Singleton: solves two problems
1.Ensure that a class has just a single instance
确保一个类只有一个实例
Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resource—for example, a database or a file.
为什么有人想要控制一个类有多少个实例呢?最常见的原因是控制对某些共享资源(例如,数据库或文件)的访问。
2.Provide a global access point to that instance.
提供该实例的全局访问点
Just like a global variable, the Singleton pattern lets you access some object from anywhere in the program. However, it also protects that instance from being overwritten by other code.
就像全局变量一样,Singleton 模式允许您从程序中的任何位置访问某些对象。但是,它还可以保护该实例不被其他代码覆盖。
Singleton: Solution
1.Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
将默认构造函数设为 private,以防止其他对象将 new 运算符与 Singleton 类一起使用。
2.Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.
创建充当构造函数的静态创建方法。在后台,此方法调用私有构造函数来创建对象并将其保存在 static 字段中。对此方法的所有后续调用都将返回缓存的对象。