单例设计模式(C#) 懒汉模式
2016-08-05 11:23
302 查看
Lazy模式的两种方式
BaseSingle见 简单模式定义方式1 代码
/// <summary> /// /// </summary> public class SafeLazySingle : BaseSingle { private static class SingleWapper { public static SafeLazySingle Instatce = new SafeLazySingle(); } private SafeLazySingle() { } public static SafeLazySingle GetInstance() { return SingleWapper.Instatce; } }
方式1 测试代码
internal delegate void InstanceFun(); public void LazySingleInstance() { SafeLazySingle.GetInstance().Method(); } /// <summary> /// 线程安全,lazy模式 /// </summary> [Test] public void MutilLazyTest() { MutilThreadTest(LazySingleInstance); }
方式2 代码
public class LazySingle : BaseSingle { private static Lazy<LazySingle> _instance = new Lazy<LazySingle>(()=>new LazySingle()); private LazySingle() { } public static LazySingle Instance { get { return _instance.Value; } } }
方式2 测试代码
public void LazySingleMethod() { LazySingle.Instance.Method(); } /// <summary> /// 线程安全,lazy模式 /// </summary> [Test] public void MutilLazySingleTest() { MutilThreadTest(LazySingleMethod); }
输出结果
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
DesignPattern.LazySingle.Method:39086322
……
相关文章推荐
- [用设计模式锻炼C#系列]之Strategy
- [用设计模式锻炼C#系列]之Decorator
- C#设计模式(2)
- C#设计模式(6)-Abstract Factory Pattern
- C#设计模式(5)-Factory Method Pattern
- 从C#的Singleton设计模式实现看.NET Framework特性对开发者的重要性
- 设计模式之C#实现(一)--AbstractFactory
- 设计模式C#描述——工厂方法模式 mutou23 [原作]
- C#设计模式学习笔记---简单工厂模式
- C#设计模式(7)-Singleton Pattern
- 设计模式之C#实现(一)--AbstractFactory(补)
- Singleton设计模式的C#实现(下)
- 设计模式之C#实现(四)---- ProtoType
- C#设计模式(3)
- C#设计模式之组合(Composite)
- [用设计模式锻炼C#系列]之Builder
- 设计模式之C#实现(三)FactoryMethod
- C#设计模式之原型(ProtoType)
- C#设计模式(3)
- C#设计模式(8)-Builder Pattern