Home > C#, Design Pattern, Programming > Singleton


Frequency of Use

Ensure a class only has one instance, and provide a global point of access to it.


Use the Singleton pattern when

  • there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Code Implemetation (C#)

using System;

namespace Singleton
    class MainClass
        public static void Main (string[] args)
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            if(s1 == s2)
                Console.WriteLine("Objects are the same Instance");


    class Singleton
        private static Singleton instance;

        protected Singleton()


        public static Singleton Instance()
            if(instance == null)
                instance = new Singleton();

            return instance;

Output Code

Objects are the same Instance



Categories: C#, Design Pattern, Programming
  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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: