Where exactly the Singleton Pattern is used in real application?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)