When should you use the singleton pattern instead of a static class? [closed]
Solution 1:
- Singletons can implement interfaces and inherit from other classes.
- Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialisation includes expensive resource loading or database connections.
- Singletons offer an actual object.
- Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.
Solution 2:
How about "avoid both"? Singletons and static classes:
- May introduce global state
- Get tightly coupled to multiple other classes
- Hide dependencies
- Can make unit testing classes in isolation difficult
Instead, look into Dependency Injection and Inversion of Control Container libraries. Several of the IoC libraries will handle lifetime management for you.
(As always, there are exceptions, such as static math classes and C# extension methods.)
Solution 3:
I'd argue the only difference is syntax: MySingleton.Current.Whatever() vs MySingleton.Whatever(). The state, as David mentioned, is ultimately "static" in either case.
EDIT: The bury brigade came over from digg ... anyhow, I thought of a case that would require a singleton. Static classes cannot inherit from a base class nor implement an interface (at least in .Net they cannot). So if you require this functionality then you must use a singleton.
Solution 4:
One of my favorite discussions about this issue is here (original site down, now linked to Internet Archive Wayback Machine.)
To summarize the flexibility advantages of a Singleton:
- a Singleton can be easily converted into a factory
- a Singleton can be easily modified to return different subclasses
- this can result in a more maintainable application
Solution 5:
A static class with a load of static variables is a bit of a hack.
/**
* Grotty static semaphore
**/
public static class Ugly {
private static int count;
public synchronized static void increment(){
count++;
}
public synchronized static void decrement(){
count--;
if( count<0 ) {
count=0;
}
}
public synchronized static boolean isClear(){
return count==0;
}
}
A singleton with an actual instance is better.
/**
* Grotty static semaphore
**/
public static class LessUgly {
private static LessUgly instance;
private int count;
private LessUgly(){
}
public static synchronized getInstance(){
if( instance==null){
instance = new LessUgly();
}
return instance;
}
public synchronized void increment(){
count++;
}
public synchronized void decrement(){
count--;
if( count<0 ) {
count=0;
}
}
public synchronized boolean isClear(){
return count==0;
}
}
The state is in ONLY in the instance.
So the singleton can be modified later to do pooling, thread-local instances etc. And none of the already written code needs to change to get the benefit.
public static class LessUgly {
private static Hashtable<String,LessUgly> session;
private static FIFO<LessUgly> freePool = new FIFO<LessUgly>();
private static final POOL_SIZE=5;
private int count;
private LessUgly(){
}
public static synchronized getInstance(){
if( session==null){
session = new Hashtable<String,LessUgly>(POOL_SIZE);
for( int i=0; i < POOL_SIZE; i++){
LessUgly instance = new LessUgly();
freePool.add( instance)
}
}
LessUgly instance = session.get( Session.getSessionID());
if( instance == null){
instance = freePool.read();
}
if( instance==null){
// TODO search sessions for expired ones. Return spares to the freePool.
//FIXME took too long to write example in blog editor.
}
return instance;
}
It's possible to do something similar with a static class but there will be per-call overhead in the indirect dispatch.
You can get the instance and pass it to a function as an argument. This lets code be directed to the "right" singleton. We know you'll only need one of it... until you don't.
The big benefit is that stateful singletons can be made thread safe, whereas a static class cannot, unless you modify it to be a secret singleton.