登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

秒大刀 博客

好好学习 天天向上

 
 
 

日志

 
 
 
 

Singleton in C#  

2007-10-16 16:09:43|  分类: C# |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

    Singleton是软件设计开发中很常用到的一种设计模式。在C#语言中实现Singleton的常见方法有下面一些,关于更详细的信息可以参阅《细颗粒度Singleton模式实现》一文。

 

  • C# 最经典Singleton模式的实现(Lazy构造方式)

public class Singleton

{

     private static Singleton instance;   // 唯一实例

     protected Singleton() { }   // 封闭客户程序的直接实例化

     public static Singleton Instance   

     {

         get

         {

              if (instance == null)

                   instance = new Singleton();

              return instance;

         }

     }

}

  • C# 通过Double Check实现的相对线程安全的Singleton模式

public class Singleton

{

     protected Singleton() { }

     private static volatile Singleton instance = null;

     /// Lazy方式创建唯一实例的过程

     public static Singleton Instance()

     {

         if (instance == null)           // 外层if

              lock (typeof(Singleton))    // 多线程中共享资源同步

                   if (instance == null)   // 内层if

                       instance = new Singleton();

         return instance;

     }

}

  • C#充分依靠语言特性实现的间接版Singleton模式

class Singleton

{

     private Singleton() { }

     public static readonly Singleton Instance = new Singleton();

}

  • 对于线程级的Singleton可以采用[ThreadStatic]Attribute来修饰

[ThreadStatic]

public static readonly Singleton Instance = new Singleton();

    以下实现利用了静态字段在第一次用到时才初始化的“延迟求值”技术:

public class Singleton

{

         protected Singleton() { }

         // Return an instance of Singleton

         public static Singleton Instance { get { return SingletonCreator.Instance; } }

 

         private sealed class SingletonCreator

         {

                   // Retrieve a single instance of a Singleton

                   private static readonly Singleton s_instance = new Singleton();

 

                   // Return an instance of the class

                   public static Singleton Instance { get { return s_instance; } }

         }

}


2011-11-15 Generic Singleton in C#
    单件(Singleton)是在实际中最常用到的设计模式之一。简洁方便的实现对开发工作非常有益。以下提供了StaticSingleton和LazySingleton两种实现。StaticSingleton会在第一次调用Instance时进行单件构造,不可进行单件生命期的精细操作;LazySingleton完全由用户控制单件的构造和生命期,对某些特定应用更为贴切。
    用法实例请参见代码注释。

#region StaticSingleton

/// <summary>

/// Implementing the Singleton Pattern in C#

/// Thread-safety without using locks

/// 所管理的对象将在第一时间由框架自动初始化并持续。

/// </summary>

/// <ref>http://www.yoda.arachsys.com/csharp/singleton.html</ref>

/// <example><code>

/// class Demo

/// {

///    public static Demo Instance { get { return StaticSingleton<Demo>.Instance; } }

/// }

/// </code></example>

public sealed class StaticSingleton<T> where T : class, new()

{

         /// <remarks>Explicit static constructor to tell C# compiler not to mark type as beforfieldinit.</remarks>

         static StaticSingleton() { }

         private static readonly T instance = new T();

         public static T Instance { get { return instance; } }

}

#endregion

 

#region LazySingleton

/// <summary>

/// Implementing the Singleton Pattern in C#

/// Thread-safety using double-check locking

/// 所管理对象的初始化和释放用户可控

/// </summary>

/// <example><code>

/// class Demo

/// {

///    private static readonly LazySingleton<Demo> singleton = new LazySingleton<Demo>(() => new Demo());

///    public static Demo Instance { get { return singleton.GetInstance(); } }

///    private Demo(){}

/// }

/// </code></example>

public sealed class LazySingleton<T> where T : class

{

         private Func<T> ctor;

         private T instance;

         private readonly object instanceLock = new object();

         public LazySingleton(Func<T> factoryMethod) { ctor = factoryMethod; }

 

         /// <summary>确保得到对象单件实例,绝不会返回null</summary>

         public T GetInstance()

         {

                   if (instance == null)

                   {

                            lock (instanceLock)

                            {

                                     if (instance == null)

                                               NewInstance();

                            }

                   }

                   Debug.Assert(instance != null);

                   return instance;

         }

         /// <summary>尝试得到对象单件实例,若尚未构造则返回null</summary>

         public T TryGetInstance() { return instance; }

         /// <summary>创建单件实例</summary>

         public T NewInstance()

         {

                   Debug.Assert(instance == null);

                   instance = ctor();

                   return instance;

         }

         /// <summary>将给定的实例指定为单件实例</summary>

         /// <param name="instance">要指定为单件实例的实例</param>

         public T NewInstance(T instance)

         {

                   Debug.Assert(this.instance == null);

                   this.instance = instance;

                   return instance;

         }

         /// <summary>删除单件实例</summary>

         public T DeleteInstance()

         {

                   T ret = instance;

                   instance = null;

                   return ret;

         }

}

#endregion

  评论这张
 
阅读(1818)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018