Wednesday, April 28, 2010

Singleton Design Pattern By Example in C#

This is part of a series of posts in which we will deal with some of the popular design patters using simple but non-trivial examples.

Singleton Pattern is probably the most well known of all design patterns.  And it is also one of the most simple.  The requirement for this pattern arises when you need to share a single instance of a class across your whole application. The download link for this sample project is available at the bottom.

 The implementation of the Singleton pattern consists of:
  • A Class with a private field pointing to its own instance.  This can be initialised on the field itself or in the Instance Getter.
  • Private constructor.  There should not be any public constructors to this class.
  • A Getter property for the Instance.
 Hence the only way to get a instance of this class is through the Instance property which returns the one and only instance. 

Why not just use a Static Class?

The advantage of using a normal class is that it can inherit from another class or implement an interface.  And also this class can be passed as a parameter in a method.


Download Sample Code

Happy Coding

Ravi