设计模式学习单件模式

单件模式(singleton)

单件模式定义了一个类只能有一个实例存在的事实。对于暴露只读数据它是很有用的,同样的还有不依赖于实例数据的静态方法。而不是每一次都创建一个类的实例,通过使用一个类的静态方法来实现单件模式,应用程序包含了对一个存在实例的引用,

如果是第一次调用返回实例的方法,单件模式就会创建实例,用任何必须的数据和返回实例来发布给调用者,紧接着的调用只是返回存在的实例,实例的生命期是应用程序域。

ASP.net中通常是指域应用程序对象(domain Application object)的生命期。

class Singleton
{
   
private static Singleton instance;
   
private static int numOfReference;
   
private string code;

   
private Singleton()
   
{
     numOfReference 
= 0;
     code 
= "Jackieli";
   }

   
public static Singleton GetInstance()
   
{
     
if(instance == null)
     
{
         instance 
= new Singleton();
     }

     numOfReference
++;
     
return instance;
   }

   
public static int Reference
   
{
      
get return numOfReference; }
   }

   
public string Code
   
{
      
get return code; }
      
set { code = value;}
   }

}


这里,要注意 构造函数要私有化,防止在外部实例化该类.实例要用静态变量返回.这是为了保证全局只有一个实例.
当然,你也可以定义一个属性来返回唯一实例.

public static Singleton Instatnce()
{
   
   
get
      
{
         
if (instance == null)
         
{
             instance 
= new Singleton;
         }

         
return instance;
      }

}
原文地址:https://www.cnblogs.com/flyinthesky/p/1215197.html