首页 > 其他 > 详细

单例模式

时间:2015-08-26 19:28:31      阅读:261      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!