Wednesday, December 18, 2013

Singleton Design Pattern - Creational Design Pattern

Singleton Design Pattern

Its creational design pattern.  Singleton pattern is to ensure that a class has only one instance and provides global point of access it.

Implementation
Singleton class have its constructor as private and have static instance of itself. Class provides a static method to get its static instance to outside world.
A simple UML of the GoF singleton is shown below:








Code for Singleton


class MySingleton
{
    private MySingleton() { }

    public static MySingleton CreateInstance()
    {
        if (singleton == null)
        {
            lock (typeof(MySingleton))
            {
                if (singleton == null)
                    singleton = new MySingleton();
            }
        }
        return singleton;
    }
    private static volatile MySingleton singleton = null;
}




0 comments:

Post a Comment

About

Powered by Blogger.