October 8, 2015

How to Use Singleton Design Pattern In Java

velozit.blogspot.com
Singleton is the simplest design pattern which has categorized under creational design patterns.Most significant difference of the Singleton design pattern is allowing application to create only one instance from start to the end of the application.Singleton manage a global instance that can be access by other instances.

Assume we have a system that can manage online users.In there, system is  counting user login events and user logout events.This is like a log file.The whole system needs only one log file and it is maintaining accurate user count.

Here a sample class file created for above scenario.Refer this code and try to understand the behavior of singleton pattern.
--source code can be not loaded because of  network issues--


Output :

output

Some of disadvantages of Singleton Design Pattern

1. Do not allow inheritance.
2. In a garbage collected environment singletons can quickly become an issue with regard to memory management.
3. Singletons are also a problem from a testing perspective. They tend to make isolated unit-tests difficult to write.
4. You can not rely that there is exactly one instance of a singleton in your application - especially when it comes to clustering
5. There is also the multi-threaded scenario where singletons can become a issue as well as a synchronization issue.

Do more coding.Explore innovations.


January 22, 2015