单例设计模式

在软件系统中,经常有这样一些特殊的类,必须保证它们在系统只只存在一个实例,才能确保它们的逻辑正确性,以及良好的效率,如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace statistic
{
    class Singleton
    {
        int x;
        int y;
        private Singleton()  //步骤1、私有化构造函数
        {
        }
        public static readonly Singleton instance = new Singleton(); //步骤2、新建一个实例设置为静态只读,并分配空间
    }

    class Program
    {
        static void Main(string[] args)
        {
            Singleton st = Singleton.instance;  //步骤3、应用
        }
    }
}

http://www.cnblogs.com/guowenhui/archive/2011/10/14/2212434.html

原文地址:https://www.cnblogs.com/lwngreat/p/4921764.html