Thursday, May 29, 2008

Singleton Confusion

I heard some developers asked about this question "If you can create a static class, Why do we need to create a Singleton Class ?"

I think the answer is straight forward.

Singleton Pattern is a pattern that will make sure there is only 1 instance. on the other hand It will make sure that developers will not be able to another instance.

Static Class will share your instance through your application. But this static class will not make sure that it will only be 1 instance of your class. Other developer which don't know where you put your static instance will able to create the new instance... and It will be any duplication and waste of resources.

Here is very simple Singleton pattern.

public class MySingleton
{
//Your exclusive instance
private static MySingleton _Instance;

//this will make sure no one can create an instance of this class.
private SampleSingleton(){}

//this static constructor will be the only who can create an instance of this class
static MySingleton()
{
//TODO: you may preinit / validation code before create an instance
_Instance = new MySingleton();
}

public static MySingleton Instance
{
get{ return _Instance;}
}
}

1 comment:

Unknown said...

There are also a lot of reasons to avoid singletons.