(一)单例模式

  所以单例模式也就是保证一个类只有一个实例的一种实现方法罢了(设计模式其实就是帮助我们解决实际开发过程中的方法, 该方法是为了降低对象之间的耦合度,然而解决方法有很多种,所以前人就总结了一些常用的解决方法为书籍,从而把这本书就称为设计模式)

  

根据字面意思写出的代码如下:

   /// <summary>
    /// 单例模式
    /// </summary>
    public class Singleton
    {
        private static Singleton _instance;

        private Singleton()
        { }

        public Singleton Instance()
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }

  如果遇到多线程的情况:线程一和线程二同时走到  if (_instance == null)时, 那么就会创建俩个或者多个实例,为了规避这种情况,需要有标识确保线程同步的锁,修改后的代码如下:

    /// <summary>
    /// 单例模式
    /// </summary>
    public class Singleton
    {
        private static Singleton _instance;

        // 定义一个标识确保线程同步
        private static readonly object locker = new object();

        private Singleton()
        { }

        public Singleton Instance()
        {
            lock (locker)
            {
                if (_instance == null)
                {
                    _instance = new Singleton();
                }
            }
            return _instance;
        }
    }

  这时完全规避了创建多个实例的情况, 但是问题来了, 每次都进行加锁时, 会造成一定性能的损耗。再次进行修改:

    /// <summary>
    /// 单例模式
    /// </summary>
    public class Singleton
    {
        private static Singleton _instance;

        // 定义一个标识确保线程同步
        private static readonly object locker = new object();

        private Singleton()
        { }

        public Singleton Instance()
        {
            if (_instance == null)
            {
                lock (locker)
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }

  这种情况完全可以避免上述遗留下的问题。

 

下面是我在项目中使用的方法:

    /// <summary>
    /// 单例模式
    /// </summary>
    public class Singleton<T>
    {
        private static T _instance;

        // 定义一个标识确保线程同步
        private static readonly object locker = new object();

        private Singleton()
        { }

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (locker)
                    {
                        if (_instance == null)
                        {
                            _instance = Activator.CreateInstance<T>();
                        }
                    }
                }
                return _instance;
            }
        }
    }

  调用方法。

Singleton<TestService>.Instance.Test();

  

 

posted @ 2017-07-12 19:33  一只大老鼠  阅读(131)  评论(0)    收藏  举报