Where exactly the Singleton Pattern is used in real application?

Solution 1:

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.

Solution 2:

Some examples:

  • Hardware access
  • Database connections
  • Config files

Solution 3:

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.