可以的。单例模式是设计模式中的一种,它的目的是保证一个类只有一个实例,并且提供一个全局访问点。
以下是一个使用 C# 写的单例模式示例,同时使用了线程安全写法:
public sealed class Singleton
{ private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
使用方法:
Singleton s1= Singleton.Instance;
Singleton s2 = Singleton.Instance;
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}