Home > .NET Development > Design Patterns – Singleton

Design Patterns – Singleton

Introduction

This article explains the Sngileton Pattern which is one of The C# Design Patterns.

The singleton pattern is used to make a class that has always only one instance, how can this be useful?

There is times that you want to have only one instance of a specific class like for example a chat window,
you want to allow each chatter to have only one opened chat window.

The Code

This can be easily done by returning one instance of the class and allow a global access to it. How?

  • make the constructor private (or protected if you plan to inherit this class before instantiating it).

    class ChatWindow
    {
    private ChatWindow() { }
    }
  • Second make a static refrence to the class

    class ChatWindow
    {
    //this is static so we can access it
    //in the next point
    private static ChatWindow chatObject;

    private ChatWindow() { }
    }
  • Third make a static function that will check if the object has been instantiated or not,
    if not, it will instantiate a new one and assign it to chatObject.

    class ChatWindow
    {
    private static ChatWindow chatObject;
    private static object syncLock = new object();

    private ChatWindow() { }

    public static ChatWindow GetObject()
    {
    if (chatObject == null)
    {
    lock (syncLock)
    {
    if (chatObject == null)
    {
    chatObject = new ChatWindow();
    }
    }
    }
    return chatObject;
    }
    }

So I can always get only the same instance,

this is the Main..


class Program
{
static void Main(string[] args)
{
ChatWindow TheOnlyChatObject = ChatWindow.GetObject();
if (TheOnlyChatObject != null)
{ Console.WriteLine("Object instantiated"); }
ChatWindow sameObject = ChatWindow.GetObject();
if (sameObject == TheOnlyChatObject)
{ Console.WriteLine("A new object is the same object"); }
}
}
Advertisements
Categories: .NET Development
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: