我有一个非常有趣的情况,我已经发现使用.net框架(任何版本)都不可能使用Singleton模式
看下面这段代码
namespace SingletonPattern
{
class Singleton
{
private static readonly Singleton instance = new Singleton();
private static int mcount = 0;
private Singleton() {
mcount += 1;
Console.WriteLine("Creating {0} instances of Singleton Class", mcount.ToString());
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
class program
{
static void Main()
{
for (int i = 0; i < 1000; i++)
{
System.Activator.CreateInstance(Type.GetType("SingletonPattern.Singleton"), true);
}
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在System.activator的帮助下,任何好友都可以打破单件模式.
谁有风险呢?
任何编写一些许可组件的人,其中许可证是作为单例模式实现的.
任何基于服务器的代码都使用Singleton模式.
也许我错了或者我的发现没有意义,但我只想分享并想知道你的看法?