单件模式

  • 整个系统中对象是唯一的
  • 也可以有固定数目个
    如:对象池、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);
        }
    }
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2021-09-30
  • 2021-12-07
猜你喜欢
  • 2021-05-21
  • 2021-05-19
  • 2021-08-17
  • 2022-12-23
  • 2021-06-13
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案