Creational design Pattern – Implementing Singleton using Dot Net

Hi,

Singleton in one of the most important of the creational design pattern. Lets start with what is a creational design pattern. Creational design pattern are design pattern which are related with the creating of objects. They define the design for the creation of an object for various usage.

[Note: you can check this previous post of mine on why to use design patterns.
http://www.vikramlakhotia.com/A_word_about_Design_Pattern.aspx ]

The main thing about the singleton design is that a class has full control over its instance creation. The class itself creates its instance and no outside object can create an instance of the class.

Often while developing an application we come across situation where the instance of a class is needed only once (or a few number of time) throughout the application. The main point is that there will be one (or few) instance of the class that will be shared through out the application and have a global point of access.

One of the most common examples of the same is DBNull class. There is only one object of the DBNull class, which is shared globally. The instance of the class is available through the value property of the same class.

Lets us now have an example of a singleton class.

public sealed class SingletonExample

{

    private static SingletonExample instanceObject;

    private SingletonExample() { }

    public static SingletonExample Value()

    {

            if (instanceObject == null)

            {

                instanceObject = new SingletonExample();

            }

            return instanceObject;

    }

}

Here we have created a class SingletonExample that is a singleton class. The class will have only one object through out the application. The instance will be available from the static method inside the class Value.

As you can see for making the class a singleton class I have created a private constructor. Now the instance of the class can only be created from inside the class. The class has also been declared as sealed so that the class can not be inherited.

In the static method Value we are first checking if an instance of class already exists. If the instance does not exists then we create and instance and than return the same instance.

Now let me go a bit deeper in it and say that as a general belief singleton does not necessarily mean that there will be only one instance of the class throughout the application. Singleton design pattern takes about the class having the control over the instance creation. Even in a singleton pattern we can have multiple instance of the same class.

A good example of the same would be a user class where by only one instance of a single user can exists in the application at a time. In this case you can have multiple instance of the same class exists but no two same instance should exists at a time. What I mean is there can more than one user in the system at one time, but two instance of the same user cannot exists at one time. Here is the example of the implementation.
[Note: I know I should have used a property instead of field, but I have chosen this so that I can keep the example small and clean]

public sealed class SingletonExample1

{

    public int userID;

    private static List<SingletonExample1> instanceObject;

    private SingletonExample1(int userID) { this.userID = userID; }

    public static SingletonExample1 Value(int UserID)

    {

        foreach(SingletonExample1 se1 in instanceObject)

        {

            if(se1.userID == UserID)

            {

                return se1;

            }

        }

        SingletonExample1 se2 = new SingletonExample1(UserID);

        instanceObject.Add(se2);

        return se2;

    }

}

Here the user of the class will pass a parameter userid. The method checks if a instance of the class for the given userid exists or not. If the user exists then the same instance is passed back otherwise we create a new instance and add it to the list and then pass it back.

As you can see in this implementation we do have multiple instance of the class but the creation of the instance is still with the class and at not time can two instance of the same user exists in the application.

Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 10/2/2007 1:05:09 PM

Interesting article, two comments:

First, your implementation of the singleton is not thread safe. Check out http://www.yoda.arachsys.com/csharp/singleton.html for info on how to properly create a tread-safe singleton class.

Second, the singleton pattern is often abused and can be an indicator of a poor design. So, while it's a useful pattern to know, it's something that should only be used in the specific scenarios that warrant it.

Posted on 10/2/2007 4:25:05 PM

Unfortunately, your first example is not thread safe and is not a good singleton pattern to follow.

http://www.yoda.arachsys.com/csharp/singleton.html

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia