zoukankan      html  css  js  c++  java
  • dotnet3.5下Singleton辅助类实现

          经常要用到Singleton模式,通常情况下我们是为那个类写一个static method来创建对象。.net3.5下,可以封装这么一个辅助类,
    看代码如下:

     1     #region Singleton
     2     /// <summary>
     3     /// Used for classes that are single instances per appdomain
     4     /// </summary>
     5     public static class Singleton
     6     {
     7         private static class Storage<T>
     8         {
     9             internal static T s_instance;
    10         }
    11 
    12         /// <summary>
    13         /// Gets the instance.
    14         /// </summary>
    15         /// <typeparam name="T">Func<T></typeparam>
    16         /// <param name="op">The op.</param>
    17         /// <returns>T</returns>
    18         /// <remark>Author : PetterLiu 2008-12-2816:02  http://wintersun.cnblogs.com </remark>
    19         public static T GetInstance<T>(Func<T> op)
    20         {
    21             if (Storage<T>.s_instance == null)
    22             {
    23                 lock (typeof(Storage<T>))
    24                 {
    25                     if (Storage<T>.s_instance == null)
    26                     {
    27                         T temp = op();
    28                         System.Threading.Thread.MemoryBarrier();
    29                         Storage<T>.s_instance = temp;
    30                     }
    31                 }
    32             }
    33             return Storage<T>.s_instance;
    34         }
    35 
    36         /// <summary>
    37         /// Gets the instance.
    38         /// </summary>
    39         /// <typeparam name="T">T</typeparam>
    40         /// <returns>T</returns>
    41         /// <remark>Author : PetterLiu 2008-12-2816:02  http://wintersun.cnblogs.com </remark>
    42         public static T GetInstance<T>()
    43             where T : new()
    44         {
    45             return GetInstance(() => new T());
    46         }
    47     }
    48     #endregion

    UnitTest:
    Test

    http://wintersun.cnblogs.com
  • 相关阅读:
    品尝阿里云容器服务:负载均衡与容器的关系
    基于微服务架构、运行于容器中的.NET Core示例应用eShopOnContainers
    基于VS2017的Docker Support体检ASP.NET Core站点的Docker部署
    用工厂模式解决ASP.NET Core中依赖注入的一个烦恼
    终于知道什么情况下需要实现.NET Core中的IOptions接口
    ASP.NET Core Web API处理HttpResponseMessage类型返回值的问题
    ASP.NET Core奇遇记:无用户访问,CPU却一直100%
    省一行是一行:在if语句中使用C# 7.0的模式匹配
    ASP.NET Core 2.0 Preview 1 中贴心的新特性
    .NET Core类库项目中如何读取appsettings.json中的配置
  • 原文地址:https://www.cnblogs.com/wintersun/p/1364023.html
Copyright © 2011-2022 走看看