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
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.