【发布时间】:2014-12-12 19:03:32
【问题描述】:
我试图为我的日志系统实现单例继承,这样我就能够将系统事件与用户行为分开。我找到了this nice post in Java。尽管存在泛型差异,但我可以实现这个附加的第一个版本(暂时非线程安全)。
public abstract class Log
{
private static volatile Dictionary<Type, Log> instances = new Dictionary<Type, Log>();
public static Log GetInstance(Type type) {
Log instance = null;
if (!Log.instances.ContainsKey(type))
{
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Default,
null,
new Type[0],
new ParameterModifier[0]);
instance = ctor.Invoke(new object[0]) as Log;
instances.Add(type, instance);
}
else
{
instance = Log.instances[type];
}
return instance;
}
private Log() { }
public class UserLog : Log
{
private UserLog() : base() { }
}
public class SystemLog : Log
{
private SystemLog() : base() { }
}
}
上面的高亮行显示了创建新实例的尝试。但是它不起作用并返回一个 ConstructorInfo 的空实例。
1) 关于如何使用 GetConstructor 方法的任何想法?我知道它有 3 个重载版本,但第一个仅适用于公共构造函数。如果我将构造函数的可见性更改为公共,我可以使用其他重载版本 (this one),但这个特定版本我什至不能使用公共构造函数。
2) 在 C# 中,是否可以像我尝试的那样从其他类调用私有构造函数?我已经用 Java 实现了它,但在 C# 中可能会有所不同。
【问题讨论】:
-
单例有私有构造函数,所以你不能使用invoke。
-
您不能调用抽象类。从那以后,让它成为一个单身人士就不行了。
-
没有办法对子类强制执行 Singleton 要求。
-
注意因为你的父类构造函数是私有的,你不能在子类中调用构造函数。 UserLog() : base() {} 将不起作用。
标签: c# design-patterns reflection singleton