5

Possible Duplicate:
What is the difference between all-static-methods and applying a singleton pattern?

I need to make a decision for a project I'm working of whether to use static or singleton.

After reading an article like this I am inclined to use singleton.

What is better to use static class or singleton?

Edit 1 : Client Server Desktop Application.

Please provide code oriented solutions.

3 Answers3

8

Your code will be more flexible if you use a singleton.

The advantage is that the code that uses the singleton doesn't need to know if it is a singleton or a transient object. Using a static class means you have to call static methods explicitly. Think about dependency injection, for example.

Moreover, singleton, as a non-static class, can still implement an interface, supports inheritance, etc. For example, you can't inherit a static class and override a virtual method in it.

5

I agree with everything Martin said, +1 to that. To add a little, also consider that today your application has a global shared object and tomorrow you decide that you want to have more than one instance of it.

If you use a singleton, all you need to do is make your constructor public. But if you decide to use a static class, the change would have to be much more intrusive.

Also if you ever decide to add unit tests to your code, replacing a singleton instance with a fake one is much easier (change in one place) compared to having to deal with a whole bunch of static functions that all share global data.

DXM
  • 20,022
1

You have not mentioned whether it is a Web application or a standalone desktop application.

If it is a Web application, Static Classes can create some major problems in a concurrent environment (because of shared data), specially when you are also using static variables and static methods.

RPK
  • 4,378
  • 11
  • 43
  • 66