设计模式:单件模式
2009-11-26 11:43
176 查看
Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点。
1. 单线程时方法
这句if (instance == null)不是线程安全的,可能产生多个实例。
2.线程安全的
对象实例由最先进入的那个线程创建,后来的线程在进入时(instence == null)为假,不会再去创建对象实例了。但是这种实现方式增加了额外的开销,损失了性能。
3. 双重锁定
避免了每个 Instance 属性方法的调用中都出现独占锁定。
4. 静态初始化
5. 延迟静态初始化
1. 单线程时方法
public sealed class Singlton { static Singlton instance = null; Singlton() { } public static Singlton Instance { get { if (instance == null) { return new Singlton(); } return instance; } } }
这句if (instance == null)不是线程安全的,可能产生多个实例。
2.线程安全的
public sealed class Singlton { static Singlton instance = null; static readonly object o = new object(); Singlton() { } public static Singlton Instance { get { lock (o) { if (instance == null) { return new Singlton(); } return instance; } } } }
对象实例由最先进入的那个线程创建,后来的线程在进入时(instence == null)为假,不会再去创建对象实例了。但是这种实现方式增加了额外的开销,损失了性能。
3. 双重锁定
public sealed class Singlton { static Singlton instance = null; static readonly object o = new object(); Singlton() { } public static Singlton Instance { get { if (instance == null) { lock (o) { if (instance == null) { return new Singlton(); } } } return instance; } } }
避免了每个 Instance 属性方法的调用中都出现独占锁定。
4. 静态初始化
public sealed class Singlton { static readonly Singlton instance = new Singlton(); static Singlton() { } public static Singlton Instance { get { return instance; } } }
5. 延迟静态初始化
public sealed class Singlton { static Singlton() { } public static Singlton Instance { get { return CreateSinglton.instance; } } class CreateSinglton { internal static readonly Singlton instance = new Singlton(); static CreateSinglton() { } } }
相关文章推荐
- Sigleton单件(创建型模式)--面向对象设计模式纵横谈讲座笔记之二
- C#设计模式之单件模式(Singleton Pattern)
- 设计模式-单件模式(Singleton Pattern)
- JavaScritp设计模式1 ----- 单件模式
- 设计模式(二)单件模式Singleton(创建型)
- [设计模式] C++设计模式-单件 Good!!!
- He 4000 ad First-设计模式:单件模式
- 浅析设计模式之单件模式
- 设计模式单件(Singleton)---对象创建型模式
- .NET设计模式(2):单件模式(Singleton Pattern)
- 设计模式学习笔记之单件模式
- 1.设计模式 - Singleton模式(单件模式)
- c++设计模式:单件模式(Singleton Pattern)
- C#设计模式——单件模式(Singleton Pattern)
- 设计模式 之 单件模式
- 设计模式之单件模式(Singleton)
- 设计模式之美:Singleton(单件)
- Head First 设计模式——单件模式(Singleton Pattern)
- C#设计模式极简单实现(1)单件模式
- 设计模式之单件模式