Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where exactly the Singleton Pattern is used in real application?

Tags:

java

singleton

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

like image 855
swati Avatar asked Jul 07 '10 05:07

swati


People also ask

Where is Singleton pattern used in real life?

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.

What is singleton class where is it used?

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.

When should we use Singleton design pattern?

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.

What is real time example of singleton class in java?

Example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class.


1 Answers

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.

like image 178
Jon Skeet Avatar answered Sep 17 '22 19:09

Jon Skeet