我尝试将模板模式应用于' hook'由布尔值' true'激活。来自默认为false的虚方法的值。所以我的实现类可以覆盖它来激活钩子。但是,钩子中的功能必须是虚拟的,因为并非所有实现类都需要实现它。下面的实现对我来说并不美观 - 有没有更好的方法,以避免默认的异常抛出?
// template pattern applied in this function
public virtual Tobject CompileEntityFromDocument<Tobject>(document document)
{
Tobject dummyObject = CreateEntity();
SetAttributesForEntity(dummyObject, null, null);
if (MustSetRelationsForEntity())
{
SetRelationsForEntity(dummyObject, null);
}
return (Tobject)dummyObject;
}
public abstract void SetAttributesForEntity(object entity, document mainDocumentToCompileFrom, List<vfield> documentFieldRecords);
public abstract Tobject CreateEntity<Tobject>();
public virtual void SetRelationsForEntity<Tobject>(Tobject entity, List<vfield> documentFieldRecords)
{
throw new NotImplementedException("This must be overridden in implementing classes");
}
public virtual bool MustSetRelationsForEntity()
{
return false;
}
答案 0 :(得分:1)
为什么不简单地在基础中将其留空,并且在必须设置关系时让派生类重写?
像这样:
// template pattern applied in this function
public virtual Tobject CompileEntityFromDocument<Tobject>(document document)
{
Tobject dummyObject = CreateEntity();
SetAttributesForEntity(dummyObject, null, null);
SetRelationsForEntity(dummyObject, null);
return (Tobject)dummyObject;
}
public abstract void SetAttributesForEntity(object entity, document mainDocumentToCompileFrom, List<vfield> documentFieldRecords);
public abstract Tobject CreateEntity<Tobject>();
public virtual void SetRelationsForEntity<Tobject>(Tobject entity, List<vfield> documentFieldRecords)
{
//Do nothing in base
}