标签:object pre led public turn get 饿汉式 ret ati
单例模式的代码:
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; } }
标签:object pre led public turn get 饿汉式 ret ati
原文地址:http://www.cnblogs.com/zhengwei-cq/p/6696565.html