I was just curious where exactly the singleton pattern is used... I know how the pattern works and where it can be used but i personally never used in any real application. Can some one give an example where it can be used.. I would really appreciate if some one can explain how and where they have used in real application. Thanks, Swati
Singleton is like a single resource which is being shared among multiple users; for example - sharing a single washing machine among all the residents in a hotel or sharing a single appliance like refrigerator among all the family members.
A Singleton class in Java allows only one instance to be created and provides global access to all other classes through this single object or instance. Similar to the static fields, The instance fields(if any) of a class will occur only for a single time.
Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.
Example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class.
Typically singletons are used for global configuration. The simplest example would be LogManager
- there's a static LogManager.getLogManager()
method, and a single global instance is used.
In fact this isn't a "true" singleton as you can derive your own class from LogManager
and create extra instances that way - but it's typically used as a singleton.
Another example would be java.lang.Runtime
- from the docs:
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
That's pretty much the definition of a singleton :)
Now the singleton pattern is mostly frowned upon these days - it introduces tight coupling, and makes things which use the singleton harder to test, as you can't easily mock out that component. If you can get away without it, so much the better. Inject your dependencies where possible instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With