单例模式的实现分为两种:饿汉式和懒汉式
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
饿汉式
在静态构造函数执行时就立即实例化
class Singleton
{
public static Singleton Instance { get; } = new Singleton();
//private static readonly Singleton _instance=new Singleton();//readonly 关键字声明实例不能被修改
//public static Singleton Instance
//{
// get
// {
// return _instance;
// }
//}等同于上面的写法
}
懒汉式
在程序执行过程中第一次需要时再实例化
public class LazySingleton
{
private static readonly Lazy<LazySingleton> _instance =
new Lazy<LazySingleton>(() => new LazySingleton());
public static LazySingleton Instance
{
get { return _instance.Value; }
}
}
网友评论