You can see this and other great articles on design patterns here.

The Singleton Design Pattern allows you to have only a single instance of an object of a particular class anywhere in the application. The pattern will work in any class library or web services in the same application domain. For example, if you have webService1 and webService2 and they are both in the same running application domain, you will see that both web services are accessing the same object instance.

Let's see an example. In the example we will have an object instance of the Robot class, and anywhere in the application it should only have one single instance of the Robot object.

Below is the UML of the Robot singleton:

Below is the code of the Robot singleton:

public class Robot
{
    private static Robot self;

    //hide the default constructor
    private Robot() { }

    public static Robot Instance()
    {
        //create instance only if we don't have one
        if (self == null)
            self = new Robot();
        return self;
    }
}

The client code(calling code) to access the singleton will be:     

Robot b = Robot.Instance();
Notice that:
  • We hide the default constructor so that the entire application can only call public static Instance method to access the singleton.
  • The private static self variable holds the actual single instance of the class.

Below are the implementation code and the output of the singleton pattern using our example. Notice that every Robot instance in the application is the same object instance:

class Program
{
    static void Main(string[] args)
    {
        Robot a = Robot.Instance();
        a.Name = "Jim";

        Robot b = Robot.Instance();
        Console.WriteLine("Robot's name is: " + b.Name);

        Robot c = Robot.Instance();
        Console.WriteLine("Robot's name is: " + c.Name);
    }
}

public class Robot
{
    private static Robot self;
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    //hide the default constructor
    private Robot() { }

    public static Robot Instance()
    {
        //create instance only if we don't have one
        if (self == null)
            self = new Robot();
        return self;
    }
}

Liked this article? You can see this and other great articles on design patterns here.

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"