Implementing the Singleton Pattern in C#
CoderSource.net
Implementing the Singleton Pattern in C# - Article by oraclequest
Level: MediumType: Article
Rating: 5Page: 1 of 2

Date: 8/11/2005 12:00:00 AM

Environment: IIS, .NET ,C#

Implementing the Singleton Pattern in C#

This article describes about design pattern namely Singleton Pattern.

Often when developing large application we come across situation when the instance of the class has to be instantiated only once with global point of access to instance. In this scenario we can use one of the singleton pattern that are commonly available. Implementing singleton pattern ensures that a class will have only one instance created and also provides a global point of access to class instance.

Let us see some of the implementation :

Ist way of implementing Singleton Pattern in C#:

Look into the following code and then we can run through it,

using System;

public class SingletonExample
{


  private static SingletonExample instance;

  private SingletonExample () {}
 

public static SingletonExample Instance
{

get
{

if (instance == null)
{

instance = new SingletonExample ();

}

return instance;

}
}
}

  The instance is created inside the Instance property method, this class can also be instantiated any subclass and other functionalities, though it may introduce unnecessary dependencies. You can notice here that instantiation is not performed until an object asks for an instance. This implementation is not a thread safe for multithreaded environments.. There can be two different threads that are evaluated for the check if (instance==null) and found it to be true, then both will create instances, this violates the singleton pattern. Also there might be a case when the instance may already have been created before the expression is evaluated but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory checks have been passed.
This approach is called as lazy instantiation. This approach avoids instantiating unnecessary singletons classes when the application starts. 


IInd way of implementing Singleton Pattern in C#: Static Initialization Pattern
In the previous example there were some short comes due to which it is not a thread safe implementation. The problem was the instancing of the objects. In this implementation we will see how to over come this problem.


public sealed class SingletonExample
{
   private static readonly SingletonExample instance = new SingletonExample ();
   
   private SingletonExample (){}

   public static SingletonExample Instance
   {
      get 
      {
         return instance; 
      }
   }
}

As you can see above, the instance is created first time when any member of the class is referenced. The common language runtime takes care of the variable initialization. The class is declared as sealed to prevent any addition of instances. Also, the variable is marked readonly, so that it can be assigned only during the static initialization or in a class constructor.

This implementation relies on the CLR to initialize the variables. It resolves the two problem namely global access and control over the way class is instantiated. The public static property provides a global access point to the instance. Also, as the constructor is private, the Singleton class cannot be instantiated outside of the class itself. Thus there is the restriction on only one instance that can exist in the system. Here as the Singleton instance is referenced by a private static member variable, therefore the instantiation of the class is not created until the class is first referenced invoking Instance property. You can see that this is slightly differed form of lazy instantiation property

The drawback of this approach is the way instantiation is controlled, This is because the fact.NET Framework performs the initialization. As use of a nondefault constructor or perform any other tasks before the instantiation is no more available. Generally, static initialization is mostly preferred choice for implementing a Singleton in .NET.


IIIrd way of implementing Singleton Pattern in C#: Simple Multithreaded Singleton Pattern

There is another way of implementing a simple multithreaded singleton patter as shown below:


public sealed class SingletonExample
{
  private static SingletonExample instance=null;
  private  static readonly object objectlockCheck = new object();

    private  SingletonExample ()
    {
    }

    public static SingletonExample Instance()
    {
        lock (objectlockCheck)
        {
            if (instance==null)
                instance = new SingletonExample ();
            return instance;
        }
    }
}

This is simple thread-safe implementation. Here the thread obtains a lock on the shared object and then checks of the existence of instance before creating the new instance. This is most apt implementation as it resolves all the memories check issues like read occurs only after the lock is obtained  and any write is done when the lock is released. Also this ensures the single thread creation. Still with this implementation there is the problem of performance that lock is acquired each time the instance is request for creation.

 

1 2

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us