码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2015-08-26 19:29:43      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

    //线程不安全的单例模式
    public class Singleton
    {
        private static Singleton singleton = null;
        public static Singleton Single
        {
            get {
                if (singleton == null)
                {
                    singleton = new Singleton();
                    return singleton;
                }
                else
                    return singleton;
            }
        }
        private Singleton()
        {
        }
    }

    //线程安全的单例模式,双重锁定
    public class ThreadSafeSingleton
    {
        private static ThreadSafeSingleton threadSafeSingleton;
        private static readonly object synRoot = new object();
        public static ThreadSafeSingleton getInstance()
        {
            if (threadSafeSingleton == null)
            {
                lock (synRoot)
                {
                    if (threadSafeSingleton == null)
                    {
                        threadSafeSingleton = new ThreadSafeSingleton();
                    }
                }
                return threadSafeSingleton;
            }
            else
            {
                return threadSafeSingleton;
            }
        }

        private ThreadSafeSingleton()
        { }
    }


    //恶汉模式的单例模式,依赖公共语言库来初始化变量
    //这种静态初始化的方式是在自己被加载时就将自己实例化,所以形象的称为饿汉式单例类
    public class SafeSingleton
    {
        private static SafeSingleton singleton = new SafeSingleton();

        private SafeSingleton()
        { }

        public static SafeSingleton getInstance()
        {
            return singleton;
        }
    }

单例模式

标签:

原文地址:http://www.cnblogs.com/FJuly/p/4761111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!