Sunday, April 28, 2013

Published 11:01 PM by with 0 comment

Singleton - [Creational Patterns]


Singleton Definition

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

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();
            if (s1 == s2)
            {
                Console.WriteLine("Indenticle Instances");
            }
            Console.ReadKey();
        }
    }
}

Singleton Class
namespace Singleton
{
    class Singleton
    {
        public static Singleton _instance;

        protected Singleton()
        {
        }

        public static Singleton Instance()
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
}

    email this       edit

0 comments: