为简化这个问题,它有点简化了。 要点是要强制从派生中调用所有基本构造函数,并禁止所有其他构造函数。
通过抽象模板强制一个专有的构造函数:
public abstract class AbstractTemplatePattern
{
protected AbstractTemplatePattern(Foo foo)
{
// do the same work for every derived class
}
}
class DerivedTemplatePattern : AbstractTemplatePattern
{
// exclusive constructor forced by template (no others allowed)
public DerivedTemplatePattern(Foo foo) : base(foo) { }
// possible too, force calling the base contructor is the main thing here!
public DerivedTemplatePattern() : base(new Foo()) { }
public DerivedTemplatePattern(Bar bar) : base(new Foo()) { }
// not allowed constructor examples
public DerivedTemplatePattern() { }
public DerivedTemplatePattern(Bar bar) { }
}
对n个互斥构造函数的明显扩展不会强制派生类中具有n个互斥构造函数,它只会强制其中之一:
public abstract class AbstractTemplatePattern
{
protected AbstractTemplatePattern(Foo foo)
{
// do the same work for every derived class
}
protected AbstractTemplatePattern(Bar bar)
{
// do the same work for every derived class
}
}
class DerivedTemplatePattern : AbstractTemplatePattern
{
// no error, but this should not be allowed, as the template gives two constructors
public DerivedTemplatePattern(Foo foo) : base(foo) { }
}
是否可以通过抽象模板来实现?
如果有帮助,可以选择实施工厂模式。