Design Patterns

Design Patterns are reusable solutions to a commonly occurring problem in software. It’s not a ready to use code instead it is more like a general template or solution for a particular problem. When you get understanding of Design Patterns then at a time designing solutions you can come across a situation like “Oh Yes! I can apply here that particular design pattern” 🙂

Design Patterns provides you a proven and tested solution to a particular problem. They speed up design process and hence enhances productivity. I’m not going to give detail introduction to Design Patterns as purpose here is to understand and see how we can apply a particular design pattern in a language here C#. Briefly, there are four basic categories of Design Patterns

  • Creational Patterns
  • Behavior Patterns
  • Structural Patterns
  • Concurrency Patterns

Personally, I have more hands on of Creational Patterns. There are numerous design patterns in each category. We will look some of the more common in them.

So Let’s begin with a very simple design pattern which I learnt first and i.e. Singleton.

Singleton Design Pattern

Singleton ensures a single instance of the class and have global access. To apply singleton to a class we make it’s constructor(s) private and the class itself creates its object. For external world to get the object of the class it uses a static method that returns the object. Lets see the code below:

public class Singleton
{
private static Singleton instance;

private Singleton() {}

public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}

Here you can see, the class has a static object of itself. Whenever the want the instance of that class you will call GetInstance Method. If the object is not initialized, the method will initialize itself or it’s done already it will give you the same object. In this way, the class will ensure a single instance and will provide a global access through static method GetInstance.

Note that it is the simple way of creating Singleton class, There are optimized version as well that provides multi-thread safe version by using lock mechanism of C# and .NET. For details please visit Implementing Singleton in C#

In the coming posts, we will see different design patterns belonging to different categories. Besides, a very good material dedicated to Patterns and Practices is available on MSDN.

Bye for now! Have a good time.