Singleton | Cheat Sheet

Creational Pattern — Design Patterns Series

Itchimonji
CP Massive Programming
3 min readMay 31, 2021

--

A Singleton is a popular and often used pattern in modern frameworks. It is a single resource shared by different users, modules, or subsystems in an application or a global configuration. Shortly explained: A Singleton is an existence of a single class instance that can be accessed globally.

Besides the controlled access to a single instance or improved operations and representation, a Singleton is hard to test because you can not create a fake object. However, you could create a subclass and extend it with a static setter for the instance.

Real-life examples

  • Single resource shared by different users: Shopping cart, parking lot, car sharing, traffic light, office printer
  • Global configuration or resource in software architecture: config-file, database-connection (get it from a connection pool), Log-Manager
  • Audio driver

Meaning

  • Existence of only a single class instance
  • Providing a global access point for this instance in your application
  • Global variable

Sometimes you should avoid global variables or instances— rather think about your system architecture.

Applicability

  • Existence of only a single class instance and providing an access point to the client
  • Instance is extensible through subclassing and clients can use the extended instance without changing existing code

Assets and Drawbacks

  • Controlled access to a single instance
  • Restricted namespace
  • Improved operations and representation (through specialization/inheritance)
  • Can be used as “global variable”
  • Hard to test, because you can not create a fake object
  • For tests you have to extend the class with a static setter for the instance

Example

A Singleton needs a private constructor and a private static instance of itself. Every time the client calls the getInstance() method, it receives an already created instance as a result.

For tests you can implement static methods to set a new instance or reset the old one.

Black tea class that implements the Singleton Pattern

Conclusion

Design Patterns are an important resource and base knowledge for every developer — they are very helpful for solving programmatic problems, help with consistent communication with other developers about system design, and serve as a significant introduction into object composition (besides inheritance) and dependency inversion.

Creational Patterns are indispensable when abstracting the instantiation process of objects. Of high importance are encapsulation of concrete classes and hiding the creational process.

--

--

Itchimonji
CP Massive Programming

Freelancer | Site Reliability Engineer (DevOps) / Kubernetes (CKAD) | Full Stack Software Engineer | https://patrick-eichler.com/links