Ensure a class only has one instance, and provide a global point of access to.多线程
保证一个类仅有一个实例,并提供一个访问它的全局访问点。ide
1. 一个类只有一个实例;函数
2. 必须自行建立实例;spa
3. 自行向整个系统提供实例线程
1. 单例模式的类只提供私有的构造函数;3d
2. 类定义含有类的静态私有对象;code
3. 提供一个静态的共有函数建立或获取自己的静态私有对象;对象
class Singleton { private static Singleton instance; //构造方法设为private,防止外界new建立实例 private Singleton() { } //获取本类实例的惟一全局访问点 public static Singleton Getinstance() { //若实例不存在,则new一个新的实例,不然返回已有实例 if (instance == null) { instance = new Singleton(); } return instance; } }
调用方法:blog
Singleton singleton = Singleton.Getinstance();
第一次引用时,才会将本身实例化生命周期
class Singleton { private static Singleton instance; private static readonly object _syncRoot = new object(); //构造方法设为private,防止外界new建立实例 private Singleton() { } //获取本类实例的惟一全局访问点 public static Singleton Getinstance() { //先判断实例是否存在,不存在再加锁处理 if (instance == null) { //lock确保当一个线程位于代码的临界区时,另外一个线程不进入临界区 //其余线程试图进入锁定的代码,它将一直等待 lock (_syncRoot) { //若实例不存在,则new一个新的实例,不然返回已有实例 if (instance == null) { instance = new Singleton(); } } } return instance; } }
在本身加载时将本身实例化
//sealed:阻止发生派生,派生可能会增长实例 public sealed class Singleton { //readonly第一次引用类的任何成员时建立实例; //公共语言运行库复测处理变量初始化 private static readonly Singleton instance = new Singleton(); private Singleton() { } public static Singleton Getinstance() { return instance; } }
1. 实例控制:阻止其余对象实例化其本身单例对象的副本,从而保证全部对象都访问惟一实例;
2. 灵活性
1. 开销:每次请求时都须要检查是否存在类的实例。用静态初始化解决此问题。
2. 可能的开发混淆:开发时不能用new关键字实例化对象。
3. 对象生命周期:不能解决删除单个对象的问题。
资源管理器
打印机