When we have Static class, what is the need for Singleton design pattern. I tried googling, but didn't get satisfactory answer.
Please tell me if anybody knows the exact diff
Printable View
When we have Static class, what is the need for Singleton design pattern. I tried googling, but didn't get satisfactory answer.
Please tell me if anybody knows the exact diff
Define your terms. What is a static class? What is a singleton?
Singleton class need to have only one instance per JVM at any given time.
In Static class we can directly access the methods/variables without creating a instance of it.
Then why singleton is required if we can achieve it through static cl
Singletons allow you the all the benefits of using object oriented programming (inheritance, polymorphism, etc.). This lets you re-use much of the existing code base.
ex.: A class which counts how many times an ActionEvent is dispatched from various components (doesn't have to be a Singleton, but just pretend it is :P).
Code java:public class ActionCounter implements ActionListener { private int counter = 0; public static ActionCounter INSTANCE = new ActionCounter(); private ActionCounter() {} public synchronized void actionPerformed(ActionEvent e) { ++counter; } public int getCounter() { return counter; } }
The two different patterns simply allow you to think about your code from a different mind set.