|
Re: Singleton vs Class with static methods
|
Posted: Sep 24, 2007 10:04 PM
|
|
> This is about the trade-offs between using a class as a > Singleton as against having a class with all Static > methods. As it is oft-repeated, using a Singleton approach > would have the following benefits: > > 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. > > Now, leaving aside the first two points for all practical > purposes (we are talking about <i>Singletons</i> only), > can anyone give an actual or real scenario/example which > illustrates point 3.
I think weather to use a class with all static methods or make it a singleton depends on the functionality that the class is providing.
I will give you a .Net example , if we have a class File which provides method to create, insert , delete , open etc. Then it is better to make all the exposed method as static instead of making it singleton. As File does need to have single instance logically. It is just providing functionality to create, delete or update. On the other hand if you have a Logger class , where you need that your application should use a single log , than single ton is the best way to implement that.
Advantages and Disadvantages of using singleton.
(1) Class with all methods as static can(in some scenario) be more efficient as there is single call to the method where as in singleton, there is one time overhead of instantiation and every time you have to call getinstance and then the method. (2) Singleton can be designed in a more thread safe manner . While to create a thread safe class with all static method a developer has to be more cautious. (3)Through Single ton class you have more control over creation of the instance , which is one of the important feature.
Pralay
|
|