首页 > 其他 > 详细

单例模式

时间:2015-11-03 10:42:48      阅读:171      评论:0      收藏:0      [点我收藏+]

 

单例模式特点:

①控制某个类型的实例数量在整个应用程序中为唯一一个。

② 为客户程序提供一个获取该实例的全局访问点。

经典模式写法:

技术分享
   public class Singleton
    {
        private static Singleton instance;
        private Singleton()
        {

        }
        public static Singleton GetInstance()
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
View Code


多线程下的单例模式写法:

技术分享
 public class Singleton
    {
        private static Singleton instance;
        private static object _lock = new object();
        private Singleton()
        {

        }
        public static Singleton GetInstance()
        {
            if (instance == null)
            {
                lock (_lock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
View Code


懒人模式写法:

技术分享
 public class Singleton
    {
        private static readonly Singleton instance = new Singleton();

        private Singleton()
        {

        }
        public static Singleton GetInstance()
        {
            return instance;
        }
    }
View Code

 

单例模式

原文:http://www.cnblogs.com/zqhxl/p/4932306.html

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