A design pattern that is used to restrict instantiation of that class to a single instance. A singleton is responsible for creating and maintaining its unique instance, and must define a public member that grants clients a global point of access to the unique instance.
Static class:
A class which has all data members as static.Static class members can be used to separate data and behavior that is independent of any object identity. It can be used when there is no data or behavior in the class that depends on object identity
Advantage of "Singleton" over the "Static Class" are
- Singletons can implement interfaces and inherit from other classes
- A singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialization includes expensive resource loading or database connections.
- Singletons offer an actual object.So we can pass it as parameters as well.
- Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.
@Anai..
ReplyDeleteI would like to add a some points to it.
While singleton is a better pattern over the static class pattern, singletons and static class patterns should not be used in the code for many reasons. Some of which are as follows.
(The following points apply to both singletons and static class patterns. For the sake of clarity, i will use only singletons)
1. A singleton class has only one instance across the entire system. Maintaining this nature itself is extremely difficult if your application runs across different VMs as in the case of distributed applications.
2. Singleton implies that you are going to have to share an instance. So you are going to have to handle thread safety issues.
3.Singletons are not easily unit-testable.The reason is every test case has to "undo" the result of its execution before the object can be handed over to another test case. This is a major head ache.
These are just some of the points that you have to consider when you are planning to use the singleton pattern.
what is lazy loading??
ReplyDelete