HeadFirst DesignPattern读书摘记(4)--单件模式
单件模式定义:取保一个类中只有一个实例,并提供一个全局访问点。
下面是实现单件模式的经典做法:
using System;
using System.Collections.Generic;
using System.Text;

namespace 设计模式
{
public class Singleton
{
//用来记录单件类中的唯一实例
private static Singleton _uniqueInstance;

//是由构造器,只有自己才能够访问自己
private Singleton()
{

}
//公开一个全局访问点,来得到这个类的实例
public static Singleton GetInstance()
{
//什么时候使用这个类,再进行实例化得到这个类的一个实例
if (_uniqueInstanc == null)
{
_uniqueInstance = new Singleton();
}
return _uniqueInstance;
}
//这个类的其他方法
}


}
下面是实现单件模式的经典做法:
using System;
using System.Collections.Generic;
using System.Text;
namespace 设计模式
{
public class Singleton
{
//用来记录单件类中的唯一实例
private static Singleton _uniqueInstance;
//是由构造器,只有自己才能够访问自己
private Singleton()
{
}
//公开一个全局访问点,来得到这个类的实例
public static Singleton GetInstance()
{
//什么时候使用这个类,再进行实例化得到这个类的一个实例
if (_uniqueInstanc == null)
{
_uniqueInstance = new Singleton();
}
return _uniqueInstance;
}
//这个类的其他方法
}

}
(注:记录一下这些内容只是以后查阅起来方便,作为自己知识积累的记录。其中有很多是参考网络上的资源,不再一一写出出处,还请原作者见谅。)


浙公网安备 33010602011771号