Hello Everyone, 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.
I used a singleton (actually a couple of them) in an application that used pureMVC. We were unhappy about the complexity this framework introduced (it became complicated and tiering to track method calls through the mvc layers). So we used a central singleton as a mediator to better separate the layers from each other.
I used the singleton pattern in an online Football Team Store System. we applied the singleton pattern to a ShoppingCart class.
You only needed one instance of the cart per an application instance. so the singleton seemed like it's the best fit for that situation.
Singleton is a nice design pattern. Before deciding on the pattern first do an in depth analysis of your problem and the solution. If in your solution some object has only one instance and you want to model that in your design then you should use singleton pattern. For example if you are modelling a PC in the software there can be only one instance of a PC with respect to your running program. As Jon Skeet said java.lang.Runtime is modelled as a singleton because for all the java objects that are loaded and running inside a java runtime there is only one instance of runtime.
Again lot of times it is used for the wrong reasons. Never create a singleton so that you can easily access the object (like Object::instance() ) from anywhere without passing the object around. The is the worst use I have ever come across.
For example running a trial version of a software with one license and one database connection ,that uses singleton pattern in real word. may be the guru jon skeet can provide example like this.