我已经声明了一个带有 protected 构造函数的单例类,并在其他类中派生。所以派生类实例可以是单例,也可以不是。
有没有办法让派生类保持单例?
最佳答案
这是我使用的良好线程安全单例类的列表:
namespace Helpers.DesignPatterns
{
public class Singleton<T> where T : class
{
private static volatile T _instance;
private static object _syncRoot = new Object();
protected Singleton()
{
}
private static T CreateInstance()
{
ConstructorInfo cInfo = typeof(T).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new Type[0],
new ParameterModifier[0]);
return (T)cInfo.Invoke(null);
}
/// <summary>
/// Точка входа синглтона
/// </summary>
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
if (_instance == null)
_instance = CreateInstance();
}
}
return _instance;
}
}
}
}
创建派生类非常简单:
class CredentialsManager : Singleton<CredentialsManager>
但通常在项目中拥有超过 1 个单例类并不是一个很好的解决方案。我有 4 个:)
关于c# - 单例类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986054/