Click here to Skip to main content
15,896,912 members
Articles / Programming Languages / C#
Article

Basic Design Pattern in C#

Rate me:
Please Sign up or sign in to vote.
1.31/5 (12 votes)
29 Jul 20062 min read 31.1K   8   8
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


Written By
Software Developer telerik
Bulgaria Bulgaria
Bachelor of Computer Systems and Technologies, Technical University.

WinForms Developer since 2006.

Comments and Discussions

 
Generalcan't lock null Pin
NickKarev231-Jul-06 0:46
NickKarev231-Jul-06 0:46 
GeneralRe: can't lock null Pin
Boyko Markov31-Jul-06 2:38
Boyko Markov31-Jul-06 2:38 
GeneralA simpler way: use static readonly [modified] Pin
Jeff X. Chang30-Jul-06 8:47
Jeff X. Chang30-Jul-06 8:47 
GeneralRe: A simpler way: use static readonly Pin
Boyko Markov31-Jul-06 3:33
Boyko Markov31-Jul-06 3:33 
GeneralThread safe, not so thread safe Pin
Ed.Poore29-Jul-06 23:09
Ed.Poore29-Jul-06 23:09 
GeneralRe: Thread safe, not so thread safe Pin
me_viper31-Jul-06 1:52
me_viper31-Jul-06 1:52 
GeneralRe: Thread safe, not so thread safe Pin
Ed.Poore31-Jul-06 2:44
Ed.Poore31-Jul-06 2:44 
GeneralRe: Thread safe, not so thread safe Pin
Boyko Markov31-Jul-06 3:30
Boyko Markov31-Jul-06 3:30 
ok, thank you, if you have any other proposals please send. I just want to make that article one good source for singleton class.

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

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