views:

1111

answers:

5

Duplicate

What’s wrong with singleton?
Singletons: good design or a crutch?
Singleton: How should it be used
What is so bad about Singletons


You can find numerous reasons for using a Singleton over a Static class. But there must surely be some situations where it is better to use a static class before a Singleton. What are they?

A: 

It's always where you don't actually need to pass the singleton instance anywhere. For example, singleton will be useful if it implements some interface, you can't do it with a static class.

Remember, every Class instance is a singleton, managed by JVM. So static class is a singleton.

alamar
+1  A: 

Static class is better for when you don't need to change the implementation. With a Singleton, you can have an interface with various implementations. A Static class, can only be an implementation.

Joshua
Interesting point. Can there ever be a case for not having flexibility for modification if the cost is trivial?
Preet Sangha
Cost is relative.
Joshua
+1  A: 

If your class doesn't store any state, then use a Static class.

If it stores state and you require a single instance, then (maybe) use a Singleton.

Otherwise use a regular class.

Patrick McDonald
+2  A: 

Having fought with the testability of consumers of static classes over the years I can honestly say that they are the work of evil minds. Seriously though, I'd use static classes for extention methods in C# but not really anywhere else.

Preet Sangha
+3  A: 

You can use static class when:

1) all its methods are utilities (nice example - class Math)

2) you don't want to deal with preserving your instance from garbage collector (in applets), but I would better use singleton there

3) you are absolutely sure that it wouldn't become stateful in the future and you are sure that you will always need only one instance of that class

If you are using singleton and in one moment you realize that you need several instances then your singleton easily can be transformed to multitone, but you'll have a problem with static class

Roman