Singleton class 的其他成员除了实例及其 get 方法之外还有什么用途?

What are the purposes of other members of a Singleton class besides the instance and its get method?

来自 GoF 的设计模式

Participants

Singleton

  • defines an Instance operation that lets clients access its unique instance uniqueinstance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++).

  • may be responsible for creating its own unique instance uniqueinstance.

Collaborations

• Clients access a Singleton instance uniqueinstance solely through Singleton's Instance operation.

在ClassSingleton中,uniqueinstance是唯一实例,Instance()是它的get方法

其他成员的目的是什么:

谢谢。

没什么特别的,或者说它与 Singleton 无关,您可以删除它或重命名它或任何您喜欢的名称。这只是一个普通的方法,与你的 class 是一个 Singleton 无关。

图中的附加方法和字段表明允许单例包含状态和行为;即单身人士不仅仅是常量。此外,单例用于子类化,这是一个经常被忽视的特性,尽管 GoF 多次提到它。

Use the Singleton pattern when... the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

因此还显示了其他方法来指示单例可能是多态的。

The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.

本书接着描述了实现此配置的多种方式。