-
Notifications
You must be signed in to change notification settings - Fork 0
Singleton
Roberto Fronteddu edited this page Feb 1, 2023
·
3 revisions
The Singleton is a Creational Design Pattern. Create a class that can be instantiated only once accessible globally through a single point.
- We want to ensure that only a single instance of a class exists
- Control Instance creation
- Constructors must not be accessible globally
- Subclassing/inheritance must not be allowed
- Keep Track of the single instance
- Give access to the instance with a public method
- A singleton class has a private INSTANCE and provides a static method to retrieve the INSTANCE.
- Any state added to a singleton becomes part of the global state of the application. Note that having a big global state is symptomatic of a bad design.
- Two options for implementing a singleton: Early initialization (Eager Singleton): Creates a singleton as soon as a class is loaded. Lazy Singleton: The instance is not created until requested.
- Use the Eager approach unless a lazy approach is needed.
- If you need to use constructor arguments, you may want to use a simple factory or factory method pattern instead.
- Make sure that singletons are not carrying a lot of mutable global states (considered anti-pattern).
- Can be deceiving in terms of true dependencies since they are globally accessible.
- Hard to unit test and mock.
- Static variables are held per class loader and not per JVM. Static variables may not be truly singletons in a web application or container (tomcat). This is a problem if the instance is tied to an external resource.
- primary intent is to ensure that only one instance of a class is ever created.
- Singleton should not use arguments.
- is primarily used to isolate client code from object creation and delegate object creation to subclasses.
- The factory method allows parametrized initialization.
- java.lang.Runtime