Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

How can I decide that I should use Static class or singleton class ??

Thanks,
Posted

The singleton pattern is a object creation control pattern. It allows you to control the instantiation of your object (in this case by restricting it to just one instance).

On the other hand, static classes are not instantiable at all.

Try and think about what abstraction model you are trying to build. If your class represents something tangible, (only one of which should ever exist) you should probably use a singleton. If you are just writing some helper methods you should probably make them static.

It's also wroth considering that the singleton pattern allows for future alteration of the creation control algorithm to allow a managed number of multiple instances.

All this considered, it's also worth noting that in many cases singleton classes don't actually bring a huge amount of benefit but add complexity and can cause tight coupling of your classes. They essentially form a global variable accessible from everywhere. Unless your class really does represent some restricted global system resource, perhaps it's worth considering some kind 'create and pass down' or an IOC/dependency injection pattern to manage your class creation instead.
 
Share this answer
 
Comments
Dalek Dave 8-Dec-10 3:48am    
Illuminating and well answered.
1. Singleton gives a reference/pointer to the class instance. You can then pass this reference as a parameter for some other function.

2. You can't extend static classes, but singletons you can, Since static classes are implicitly sealed.

3. with Singleton you can control the amount of users that can use it at the same time.
 
Share this answer
 
Static is a concept from the language point of view. Static means you dont create an object.

But Singleton is a concept which lets you create only one instance variable.

It depends on your requirement. If you can tell me what is your requirement, it would be better to give you answer.
 
Share this answer
 
Try google.[^]
 
Share this answer
 
When you want certain methods to be accessible without creating an instance then create it as static. Static class is used for shared variable usage mostly. Even you can create static methods and vars in non-static class also.

For more details and example you should use Google. You can search for details that match your particular requirements.
 
Share this answer
 
v2
Comments
Pete O'Hanlon 6-Dec-10 13:46pm    
This doesn't really answer the OPs question, now does it? You've added exactly zero to his ability to make an informed decision here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900