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

来源:互联网 发布:js slice string 编辑:程序博客网 时间:2024/06/04 19:42
 单件模式
  • 整个系统中对象是唯一的
  • 也可以有固定数目个
    如:对象池、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);
        }
    }
}
原创粉丝点击