(吐血中,优快云的录入功能总是有问题,害得我录入3次才搞定)
Singleton模式的特点:
-
私有构造函数
-
创建类的可变数量(不一定是一个)的实例
特别要注意的是Singleton可以创建可变数量的实例。
C#代码:
using System;
class Singleton 
...{
private static Singleton singleton = null;
public static Singleton Instance() 
...{
if (null == singleton)
singleton = new Singleton();
return singleton;
}
//私有构造函数
private Singleton() 
...{
}
}
class Application 
...{
public static void Main() 
...{
Singleton s1 = Singleton.Instance();
//Singleton s2 = new Singleton(); //错误:构造器不可访问
Singleton s2 = Singleton.Instance();
if (s1.Equals(s2)) // 引用相等
Console.WriteLine("Instances are identical");
}
}
以下是输出结果:
Instances are identical
本文介绍了C#中Singleton模式的应用,展示了如何通过私有构造函数和静态方法来确保类只有一个实例,并提供了完整的代码示例。
1万+

被折叠的 条评论
为什么被折叠?



