C#实现类只实例化一次(被多个类访问调用)

C#简单写法如下:

public  class  Singleton
{
     private  static  Singleton _instance =  null ;
     private  Singleton(){}
     public  static  Singleton CreateInstance()
     {
         if (_instance ==  null )
         {
             _instance =  new  Singleton();
         }
         return  _instance;
     }
}
 

单例模式特点:

单例类只能有一个实例。

单例类必须自己创建自己的唯一实例。

单例类必须给所有其它对象提供这一实例。

猜你喜欢

转载自www.cnblogs.com/asdyzh/p/9957481.html
今日推荐