This content has been marked as final. Show 4 replies
What if you have to load resources from a database for application configuration. If you use static you will always load all config items even if you did not necessarily need them, and with singleton you could lazy load. So it doesn't answer your question about Polymorphism, however its a reason that it would make more sense to use Singleton.
As far as polymorphism you can have a logger that may need to implement different interfaces so that the logger can be used by multiple parts of your system in a more generic way. You may be able to pass around a logger for whatever reason and use the interface that it implements. Maybe not the greatest idea but its the only thing that comes immediately to mind.
user12965244 wrote:The Singleton Pattern is a common way to implement the idea of a single instance.
Same purpose can be achieved using classes with static member variables and static methods.
Your question is nothing more than an embodiment of the concept without using the pattern.
user12965244 wrote:As jschell had mentioned, singleton pattern is a cleaner way of doing the task.
Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods.
I can think of at least one important difference. A non-singleton class (with static members) can be instantiated many times. That can lead to class users (rather than the class writer who knows very well that instantiation is purposeless) to create instances and use it. It leads to memory waste. Here is a case where an informed class writer can implement the singleton pattern so that others (class users) are forced to use the class in a memory efficient manner. This memory efficiency may not be important in all the applications, but where there is a possibility of using a massive number of such objects, this can mean saving memory and cut down related memory management times.
Well, in addition to what Kamal has mentioned, singleton is just a pattern defined for solving problems and it is independent of in which language it is implemented.
We implement singleton using static keyword.
Static is a java construct while singleton is more or like design principle.
Edited by: patilKetan on Dec 14, 2012 10:29 AM