Patterns in SOME –Singleton

Code in C#:
 
namespace Singleton_DesignPattern
{
     using System;
 
     class Singleton
     {
         private static Singleton _instance;
        
         public static Singleton Instance()
         {
              if (_instance == null)
                   _instance = new Singleton();
              return _instance;
         }
         protected Singleton(){}
 
         // Just to prove only a single instance exists
         private int x = 0;
         public void SetX(int newVal) {x = newVal;}
         public int GetX(){return x;}        
     }
 
     ///<summary>
     ///    Summary description for Client.
     ///</summary>
     public class Client
     {
         public static int Main(string[] args)
         {
              int val;
              // can't call new, because constructor is protected
              Singleton FirstSingleton = Singleton.Instance();
              Singleton SecondSingleton = Singleton.Instance();
 
              // Now we have two variables, but both should refer to the same object
              // Let's prove this, by setting a value using one variable, and
              // (hopefully!) retrieving the same value using the second variable
              FirstSingleton.SetX(4);
              Console.WriteLine("Using first variable for singleton, set x to 4");      
 
              val = SecondSingleton.GetX();
              Console.WriteLine("Using second variable for singleton, value retrieved = {0}", val);       
              return 0;
         }
     }
}
 
Code in SOME:
  
CSingleton      -> CSingleton[_instance]
       v_()                                                                                                                 //protected constructor;
       CSingleton s_Instance()                                    //static function
       int X                                                                                                  //property with getter and setter
 
CClient
       main
      
CClient.main
{
       int val;                   //"int" will be reserved as a unknown type
       CSingleton firstSingleton = CSingleton.Instance()                     //static method invoke
       {
              <% if (_instance == null) {%>                   
                     _instance.();
              <% } %>
             
              _instance;                            //return object
       };
       CSingleton secondSingleton = CSingleton.Instance();                //the second invoking, need not unfold
 
       firstSingleton.X = 4;                          
       val = secondSingleton.X;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值