单例模式

单例模式的代码:

1、懒汉式:在对象不存在的时候才创建,考虑了多线程

class Singleton
    {
        //提供一个静态的属性
        private static Singleton singleton;
        private static readonly object syncRoot = new object();
        //将构造器私有,不让外部NEW
        private Singleton() { }
        //对外提供一个公有的方法可以得到这个类
        public static Singleton Getinstance() {
            if (singleton == null) {
                //加锁
                lock (syncRoot)
                { 
                if (singleton == null)
                {
                    singleton = new Singleton();
                }
                }
            }
           
            return singleton;
        }
    }

 

2、饿汉式:在自己被加载时就将自己实例化

public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();
        private Singleton() {
            
        }
        public Singleton GetInstance() {
            return instance;
        }
    }

 

posted @ 2017-04-11 21:52  爱生活,爱代码  阅读(131)  评论(0编辑  收藏  举报