现在的位置: 首页 > 综合 > 正文

NET常用设计模式——单件模式

2013年12月06日 ⁄ 综合 ⁄ 共 927字 ⁄ 字号 评论关闭
单件模式

  • 整个系统中对象是唯一的
  • 也可以有固定数目个
    如:对象池、portal中的配置对象 当前httpcontext appdomain

应用实列(一)

using System;
namespace CSDesingPattern
{
    
class Singleton
    {
        
private static Singleton mInstance;
        
private int x = 0;

        //私有构造函数
        private Singleton() { }

       //实现单件实例
        public static Singleton GetObject()
        {
            
if (mInstance == null)
                mInstance 
= new Singleton();
            
return mInstance;
        }

        public void SetX(int newVal)
        {
            x 
= newVal;
        }

        public int GetX()
        {
            
return x;
        }

        static void Main(string[] args)
        {

            int val;
            Singleton s1 
= Singleton.GetObject();
            Singleton s2 
= Singleton.GetObject();
            Console.WriteLine(
"将Singleton对象中的X设置为10");
            s1.SetX(
10);
            val 
= s2.GetX();
            Console.WriteLine(
"使用第二个Singleton变量读取X的值 x={0}", val);
        }
    }
}

抱歉!评论已关闭.