Singleton
Intent
Restrict the instantiation of a class to a singular instance.
Provide easy access to that instance.
Problems
How to avoid global instances that pollute global namespace and permit lazy/eager instantiation.
How to ensure only one instance of a class is ever created.
How to provide universal and easy access to that single instance.
Solution
Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
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.
Advantages
β You can be sure that a class has only a single instance. β You gain a global access point to that instance. β The singleton object is initialized only when itβs requested for the first time.
Disadvantages
β Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily. β Increased coupling to a singleton instance can introduce difficulties with unit testing. β Singletons also violate the single-responsibility principle because they are responsible for enforcing their own uniqueness along with performing their normal functions. β The pattern requires special treatment in a multi-threaded environment so that multiple threads wonβt create a singleton object several times. β It may be difficult to unit test the client code of the Singleton because many test frameworks rely on inheritance when producing mock objects. Since the constructor of the singleton class is private and overriding static methods is impossible in most languages, you will need to think of a creative way to mock the singleton. Or just donβt write the tests. Or donβt use the Singleton pattern.
Implementation
Singleton can be implemented by,
Eager Initialization
Lazy Initialization (thread safe)
Thread-safe implementation
Double check locking
Inner static class
Enum based Singleton
Note
π‘ Is Singleton pattern still part of GoF pattern, read what GoF authors have to say about it here. π‘ How single is singleton in Java, read more about it here. π‘ Breaking singleton in Java, interesting read here
Last updated