Thursday, March 28, 2013

C# Design Patterns : Singleton

Design patterns are recurring solutions to software design problems we find again and again in real-world object oriented application development. Design patterns are there to address a variety of design problems, from small issues to large, architecture-level problems. Here, I am starting a thread which explains different categories of design patterns and their usage. Design patterns are not language specific. Here I have tried to use C# to demonstrate design patterns examples. Design patterns are categorized in three groups: Creational, Structural, and Behavioral. I will be using following format to explain design pattern to make it consistent across all patterns. Name and Category: Describes the name of the pattern and category of pattern (Creational, Structural, or) Behavioral). Intent: It describes what kind of design problem this pattern addresses. Motivation: A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem. Consequences: It will describe the trade-offs of design pattern.

In this article we will have a look at Singleton design pattern. Name and Category: Singleton (Creational Pattern)

Intent: Ensure a class only has one instance, and provide a global point of access to it.

Motivation: Sometimes we want just a single instance of a class to exist in the system For example;

we want just one window manager. Or just one factory for afamily of products. Let us look into implementation.

How can I make only one instance of my class?

First, we will create a private constructor of our class. When constructor is a private then object of that class can not be created at all.

Here, we are restricting user from creating an instance of a class. But as per our requirement we need to have one and only one constructor. In order to achieve that, we will create a one static method which in turn returns an object of class. Here, is how it goes:

// Class : Singleton.cs

using System;

using System.Collections.Generic;

using System.Text;

namespace DesignPattern

{

class Singleton

{

private static Singleton singleton = null;

/*** Returns a reference to the single instance.

* Creates the instance if it does not yet exist.

* (This is called lazy instantiation.) */

public static Singleton Instance()

{

if (null == singleton)

singleton = new Singleton();

return singleton;

}

/** The Singleton Constructor.

* Note that it is private!

* No client can instantiate a Singleton object! */

private Singleton() { }

}

}

Here, we have a static method Instance() which takes care of single instance.

In this method first we check whether the static private variable singleton is created or not.

If it is null it will create a constructor.

If it is not null it will return the existing one.

So we are sure that only one instance of our class will be created.

Now let us think in different way.

If two threads are trying to access the Instance () method at the same time what will happen? In that case we will be having two instance of our class. It means our class is not a singleton. right?? So, how can we achieve singleton object?

// Class : Singleton.cs

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading;

namespace DesignPattern

{

class Singleton

{

private static Singleton singleton = null;

// Lock synchronization object

private static object syncLock = new object();

/*** Returns a reference to the single instance.

** Creates the instance if it does not yet exist.

* (This is called lazy instantiation.) */

public static Singleton Instance()

{

/* Support multithreaded applications through

* 'Double checked locking' pattern which (once

* the instance exists) avoids locking each

* time the method is invoked*/

if (null == singleton)

{

lock (syncLock)

{

if (singleton == null)

{

singleton = new Singleton();

}

}

}

return singleton;

}

/** The Singleton Constructor.

* Note that it is private!

* No client can instantiate a Singleton object! */

private Singleton()

{}

}

}

This will make sure that only single instance of class will be created. Consequences: Benefits: 1) Controlled access to sole instance.

No comments:

Post a Comment

Software Development Blogs - BlogCatalog Blog Directory RSS Search Technology Blogs - Blog Rankings Blog Directory