专注

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

单例模式是设计模式中入门级的一种模式, 但是大数人对它的理解还是比较浅溥,网上看到一篇介绍单例模式比较全面的文章 ,地址:http://www.cnblogs.com/TomXu/archive/2011/12/19/2291448.html 。

列举几种单例的写法,包括泛型单例。

版本1:

 public sealed class Singleton
    {
        // 依然是静态自动hold实例
        private static volatile Singleton instance = null;
        // Lock对象,线程安全所用
        private static object syncRoot = new Object();

        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Singleton();
                    }
                }

                return instance;
            }
        }
    }

  版本2:

 public class Singleton
    {
        // 因为下面声明了静态构造函数,所以在第一次访问该类之前,new Singleton()语句不会执行
        private static readonly Singleton _instance = new Singleton();

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

        private Singleton()
        {
        }

        // 声明静态构造函数就是为了删除IL里的BeforeFieldInit标记
        // 以去北欧静态自动在使用之前被初始化
        static Singleton()
        {
        }
    }

  这种方式,其实是很不错的,因为他确实保证了是个延迟初始化的单例(通过加静态构造函数)


版本3(泛型):

 public abstract class Singleton
    {
        private static readonly Lazy<T> _instance
          = new Lazy<T>(() =>
          {
              var ctors = typeof(T).GetConstructors(
                  BindingFlags.Instance
                  | BindingFlags.NonPublic
                  | BindingFlags.Public);
              if (ctors.Count() != 1)
                  throw new InvalidOperationException(String.Format("Type {0} must have exactly one constructor.", typeof(T)));
              var ctor = ctors.SingleOrDefault(c => c.GetParameters().Count() == 0 && c.IsPrivate);
              if (ctor == null)
                  throw new InvalidOperationException(String.Format("The constructor for {0} must be private and take no parameters.", typeof(T)));
              return (T)ctor.Invoke(null);
          });

        public static T Instance
        {
            get { return _instance.Value; }
        }
    }

  

我们来看看是如何实现的:

  1. 声明抽象类,以便不能直接使用,必须继承该类才能用
  2. 使用Lazy<T>作为_instance,T就是我们要实现单例的继承类
  3. Lazy类的构造函数有一个参数(Func类型),也就是和我们的版本6一样
  4. 根据微软的文档和单例特性,单例类的构造函数必须是私有的,所以这里要加相应的验证
  5. 一旦验证通过,就invoke这个私有的无参构造函数,不用担心他的效率,因为他只执行一次!
  6. Instance属性返回唯一的一个T的实例

我们来实现一个单例类:

    class MySingleton : Singleton<MySingleton>
{
int _counter;

public int Counter
{
get { return _counter; }
}

private MySingleton()
{
_counter = 0;
}

public void IncrementCounter()
{
++_counter;
}
}

这个例子,在一般情况下没问题,但是并行计算的时候还是有问题的,因为上述的泛型版本的代码使用的Lazy<T>能确保我们在创建单例实例的时候是线程安全的,但是不意味着单例本身是线程安全的,我们来做个例子看看:

        static void Main(string[] args)
{
Parallel.For(0, 100, i =>
{
for (int j = 0; j < 1000; ++j)
MySingleton.Instance.IncrementCounter();
});

Console.WriteLine("Counter={0}.", MySingleton.Instance.Counter);
Console.ReadLine();
}

通常Counter的结果是小于100000的,因为单例里的IncrementCounter方法的代码本身不在线程安全的保护之内,所以如果我们想得到准确的100000这个数字的话,我们需要改一下MySingleton的IncrementCounter方法代码:

        public void IncrementCounter()
{
Interlocked.Increment(ref _counter);
}

这样,结果就完美了

posted on 2012-02-13 15:51  中金黄金  阅读(179)  评论(0编辑  收藏  举报