Introducing the Singleton Pattern

According to the Gang of Four, the Singleton's intent is to

Ensure a class only has one instance, and provide a global point of access to it.[2]

[2] Gamma, E., Helm, R., Johnson, R., Vlissides, J., Design Patterns: Elements of Reusable Object-Oriented Software, Reading, Mass.: Addison-Wesley, 1995, p. 127.

The Singleton pattern works by having a special method that is used to instantiate the desired object.

  • When this method is called, it checks to see if the object has already been instantiated. If it has, the method simply returns a reference to the object. If not, the method instantiates it and returns a reference to the new instance.

  • To ensure that this is the only way to instantiate an object of this type, ...

Get Design Patterns Explained: A New Perspective on Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.