C#实现类只实例化一次(被多个类访问调用)

C#简单写法如下:

public class Singleton
{
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            _instance = new Singleton();
        }
        return _instance;
    }
}
 

单例模式特点:

单例类只能有一个实例。

单例类必须自己创建自己的唯一实例。

单例类必须给所有其它对象提供这一实例。

posted on 2018-11-14 13:28  asdyzh  阅读(1118)  评论(0编辑  收藏  举报

导航