单例模式确保一个类仅有一个实例,并提供一个全局访问点。
示例代码:
public class Singleton
{
// 私有静态变量,存储唯一实例
private static Singleton _instance;
// 私有构造函数,防止外部实例化
private Singleton() {}
// 公共静态方法,返回实例对象
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
// 可以添加其他公共方法
public void SomeMethod()
{
// 实现功能
}
}