单例模式Singleton Pattern
用来创建独一无二的,只能有一个实例的对象。Ensure a class has only one instance and provide a global point of access to it.
有些对象我们只需要一个实例,例如线程池、缓存、处理偏好设置和注册表对象、日志对象、充当打印机、显卡等设备的驱动程序对象。如果制造出多个实例,就会导致许多问题产生,例如:程序的行为异常、资源使用过量,或者是不一致的结果。
虽然全局变量也给只有一个全局的访问点,但是如果将对象赋给一个全局变量,那么必须在程序一开始就创建好对象,如果这个对象非常耗费资源,而程序在这次的执行过程中又一直没有用到它就会形成浪费。
public class Singleton<T> where T : new()
{
Singleton()
{
}
public static T Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly T instance = new T();
}
}
参考:
http://www.yoda.arachsys.com/csharp/singleton.html
http://www.dofactory.com/Patterns/PatternSingleton.aspx#intent
posted on 2010-07-07 13:14 NewSunshineLife 阅读(181) 评论(0) 收藏 举报
浙公网安备 33010602011771号