单例模式怎么继承,我一个一个写不安全也更复杂,但是我不知道要怎么继承。
2条回答 默认 最新
- hzlcsv 2024-06-21 14:10关注
public abstract class BaseSingleton<T> where T : BaseSingleton<T> { private static BaseSingleton<T>? _instance; public static BaseSingleton<T> Instance => _instance ?? throw new InvalidOperationException("instance not created"); protected BaseSingleton() { //if(_instance is not null) //{ // throw new InvalidOperationException("instance already created"); //} _instance ??= this; } } public class SingletonClass1 : BaseSingleton<SingletonClass1> { public SingletonClass1() { } } public class SingletonClass2 : BaseSingleton<SingletonClass2> { public SingletonClass2() { } } public class Singleton1 { public static Singleton1 Instance => SingletonHelper<Singleton1>.GetInstance(); public Singleton1() { } } public class Singleton2 { public static Singleton2 Instance => SingletonHelper<Singleton2>.GetInstance(() => new Singleton2()); public Singleton2() { } } public static class SingletonHelper<T> where T : class { private static readonly object _lock = new(); private static T? _instance; public static T GetInstance(Func<T>? func = null) { if (_instance is null) { lock (_lock) { func ??= Activator.CreateInstance<T>; _instance ??= func(); } } return _instance; } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥20 Github上传代码没有contribution和activity记录
- ¥20 SNETCracker
- ¥15 数学建模大赛交通流量控制
- ¥15 为什么我安装了open3d但是在调用的时候没有报错但是什么都没有发生呢
- ¥50 paddleocr最下面一行似乎无法识别
- ¥15 求某类社交网络数据集
- ¥15 靶向捕获探针方法/参考文献
- ¥15 很抱歉出现错误word不能启动(24),如何解决?
- ¥15 javascript下载网络图片
- ¥15 excel中的填充效果 对应poi的哪个对象啊