Static classes can have only static variables which will not participate in Serialization.
Singleton classes are best in that case.
We cant always depend on order of Static Initialization. By explicitly initializing our singleton classes we can be sure that someone doesn’t destroy our carefully crafted static initialization bootstrap code by accidentally calling something when it shouldn’t be.
You can't extend static classes, but singletons you can.
For library code static classes can be nice, such as the static System.Math class in C#.
With Singleton, you can keep track of who's using it easily. This is because you need to call the getInstance() or whatever method which returns an instance of the class.
Also, because of the above, you can control the amount of actual instances. In some special cases, it might be useful to have multiple instances of the singleton class, for example for load balancing.
Static classes are stateless. If state is required Singleton can be used.
1. You can control the number of instances. ie, it's not actually *Single*ton.
2. You can sub-class a Singleton while it doesn't make sense to sub-class a class with only static methods.
3. You can control the creation of the actual instance whereas a static approach wouldn't give that flexibility.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment