单例模式

单例类:

public class Singleton
{
    private static Singleton _instance;//定义一个私有Singleton类型字段,此处不实例化
    //将构造函数设为private,防止通过new实例化对象
    private Singleton()
    { 
            
    }
    //获取实例,并加入判断逻辑,保证实例只被创建一次
    public static Singleton Instance()
    {
        if (_instance == null)
        {
            _instance = new Singleton();
            return _instance;
        }
        else
        {
            return null;
        }
    }
}

调用:

Singleton s1 = Singleton.Instance();
if (s1 != null)
{
    Console.WriteLine("成功打开s1");
}
else
{
    Console.WriteLine("不能再打开s1");
}
// 创建一个实例s2
Singleton s2 = Singleton.Instance();
if (s2 != null)
{
    Console.WriteLine("成功打开s2");
}
else
{
    Console.WriteLine("不能再打开s2");
}

运行结果:

原文地址:https://www.cnblogs.com/genesis/p/5029548.html