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

让人想犯罪 __ 提交于 2019-12-11 10:48:38

问题


From Design Pattern by 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.

In Class Singleton, uniqueinstance is the unique instance, and Instance() is its get method.

What are the purposes of the other members:

  • method SingletonOperation(),
  • method GetSingletonData(), and
  • field singletonData?

Thanks.


回答1:


Nothing in particular, or rather say it has nothing to do with Singleton , you can just remove it or rename it or whatever you like. It's just a normal method and has nothing to do to your class being a Singleton.




回答2:


The additional methods and field in the diagram show that singletons are allowed to include state and behavior; i.e. singletons are not just constants. Furthermore, singletons are intended for subclassing, a feature which is often overlooked, despite the GoF mentioning it several times.

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.

So the additional methods are also shown to indicate that singletons may be polymorphic.

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.

The book goes on to describe multiple ways in which this configuration may be achieved.



来源:https://stackoverflow.com/questions/46480156/what-are-the-purposes-of-other-members-of-a-singleton-class-besides-the-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!