C# 设计模式 - 单例模式 演示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBImportTool.Sgile
{
    //第一种单例模式Demo
    public class A
    {
        private volatile static A _instance = null;
        private static readonly object lockHelper = new object();
        private A() { }
        public static A CreateInstance()
        {
            // 判断如果没有实例过,则进行实例化创建.
            
// 瞬间触发量不高的网站,不需要此判断步骤.
            if (_instance == null)
            {
                //锁机制.防止重复实例化.
                lock (lockHelper)
                {
                    if (_instance == null)
                    {
                        _instance = new A();
                    }
                }
            }
            return _instance;
        }
    }

    //第二种单例模式Demo
    public sealed class B
    {
 
        B() { }
        public static B GetInstance()
        {
            return B1.b;
        }
        class B1
        {
            static B1()
            {
            }
            internal static readonly B b = new B();
        }
    }
}
posted @ 2014-10-14 09:58  迦南邪恋  阅读(211)  评论(0)    收藏  举报