首页 > 其他 > 详细

单例类

时间:2014-05-09 23:47:53      阅读:720      评论:0      收藏:0      [点我收藏+]

 

   1:   
   2:  using System;
   3:  using System.Collections.Generic;
   4:  using System.Text;
   5:  using System.IO;
   6:  using System.Runtime.Serialization.Formatters.Binary;
   7:  using System.Runtime.Serialization;
   8:   
   9:  namespace AkDTH.Common
  10:  {
  11:      /// <summary>
  12:      /// 单例模式泛型类
  13:      /// </summary>
  14:      public sealed class SingleObject<T> where T : new()
  15:      {
  16:          #region GetInstance  采用lock锁定线程判断方式
  17:          static readonly object padlock = new object();
  18:          private static T singleObject = default(T);
  19:          /// <summary>
  20:          /// 单例模式,返回SingleObject实例
  21:          /// </summary>
  22:          /// <returns>返回具体的泛型类</returns>
  23:          public static T GetInstance()
  24:          {
  25:              if (singleObject == null)
  26:              {
  27:                  //利用辅助对象锁定当前线程
  28:                  lock (padlock)
  29:                  {
  30:                      //双重判断服务对象是否为空
  31:                      if (singleObject == null)
  32:                      {
  33:                          singleObject = new T();
  34:                      }
  35:                  }
  36:              }
  37:              return singleObject;
  38:          }
  39:          #endregion
  40:          #region 属性:Instance  第二种单例方法:采用内部嵌套类来延迟产生单例对象
  41:          /// <summary>
  42:          /// 返回单例对象的属性
  43:          /// 只要不访问Instance属性,访问该类中其他方法都不会初始化对象,
  44:          /// 实现了延迟加载
  45:          /// </summary>
  46:          public static T Instance
  47:          {
  48:              get
  49:              {
  50:                  //调用内部嵌套类,利用嵌套类来延迟产生对象实例
  51:                  return Nested.instance;
  52:              }
  53:          }
  54:          /// <summary>
  55:          /// 密封的内部嵌套辅助类,辅助创建单例对象
  56:          /// </summary>
  57:          sealed class Nested
  58:          {
  59:              /// <summary>
  60:              /// 静态化构造方法,避免被new
  61:              /// </summary>
  62:              static Nested()
  63:              {
  64:              }
  65:              /// <summary>
  66:              /// 只读的父类型属性
  67:              /// </summary>
  68:              internal static readonly T instance = new T();
  69:          }
  70:          #endregion
  71:   
  72:   
  73:          
  74:      }
  75:  }

单例类,布布扣,bubuko.com

单例类

原文:http://www.cnblogs.com/maomao999/p/3718716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!