Click here to Skip to main content
Click here to Skip to main content

Basic Design Pattern in C#

, 29 Jul 2006
Rate this:
Please Sign up or sign in to vote.
Describes the Singleton class

Introduction to Singleton

I'll start my article with one popular non-software example for Singleton. Non-software Example

The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, "The President of the United States" is a global point of access that identifies the person in the office. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

So sometimes in software engineering we need to have only one instance of a class which can coordinate the behaviour of our object. For example: OS should have only one Window Manager, our application should have only one mouse pointer, etc. Singleton is a class which we can use in such situations. It is very popular pattern in OOP. Its access modifier is sealed so we can't have is-a relationship i.e Singleton class cannot be inherited. Its constructor's access modifier is private i.e we can't create new instances. The main question is, how we access to Singleton class. We must have a private field that will hold our only instance, and a static method GetInstance() that returns our only instance. It is possible to use a property instead of method, too.

sealed class SingletonClass
{
  private static SingletonClass myInstance = null;
  private SingletonClass(){}

  public static SingletonClass GetInstance()
  {
    if ( myInstance == null )
          myInstance = new SingletonClass();
      return myInstance;
  }
}

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation. Let's make our GetInstance() method thread safe. We can achieve that by simply adding the lock keyword. That approach is known as Double-Check Lock with method

 public static SingletonClass GetInstance()
  {
    if (myInstance  == null) 
    lock( typeof(SingletonClass) )
    {
      if ( myInstance == null )
          myInstance = new SingletonClass();
    }
     return myInstance;
  }
We can use a property instead of method.
public static SingletonClass Instance
  {
    get
    {
      if (myInstance == null)
        lock (typeof(SingletonClass))
        {
          if (myInstance  == null)
            myInstance  = new SingletonClass();
        }
      return myInstance;
    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Boyko Markov
Software Developer telerik
Bulgaria Bulgaria
Bachelor of Computer Systems and Technologies, Technical University.
 
WinForms Developer since 2006.

Comments and Discussions

 
Generalcan't lock null PinmemberNickKarev231-Jul-06 0:46 
GeneralRe: can't lock null PinmemberBoyko Markov31-Jul-06 2:38 
GeneralA simpler way: use static readonly [modified] PinmemberJeff X. Chang30-Jul-06 8:47 
GeneralRe: A simpler way: use static readonly PinmemberBoyko Markov31-Jul-06 3:33 
GeneralThread safe, not so thread safe PinmemberEd.Poore29-Jul-06 23:09 
GeneralRe: Thread safe, not so thread safe Pinmemberme_viper31-Jul-06 1:52 
GeneralRe: Thread safe, not so thread safe PinmemberEd.Poore31-Jul-06 2:44 
GeneralRe: Thread safe, not so thread safe PinmemberBoyko Markov31-Jul-06 3:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 30 Jul 2006
Article Copyright 2006 by Boyko Markov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid