学习的点点滴滴

Email : 107311278@qq.com
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

单件模式 Singleton

Posted on 2013-02-05 11:49  v薛定谔的猫v  阅读(99)  评论(0)    收藏  举报

概念描述:

  Singleton 模式要求一个类只有一个实例,提供了一个全局的访问.这个设计模式是比较简单的设计模式。

类图:

  

C#代码实现:

单线程使用:

public class Singleton
{
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton getInstance()
    {
        if(_instance == null)

        {
            _instance = new Singleton();

        }

        return _instance;
    }

}

多线程:

public class Singleton
{
    private volatile static Singleton _instance = null;
    private static readonly object lockHelper = new object();
    private Singleton(){}
    public static Singleton getInstance()
    {
        if(_instance == null)
        {
            lock(lockHelper)
            {
                if(_instance == null)
                     _instance = new Singleton();
            }

        }

        return _instance;
    }

}