模板模式的替代方案,其中实现可以具有属性



我使用了一系列模板模式类来表示不同类型的事件。

internal abstract class DayEndingEvent : Event
{  
internal void OnDayEnding(object? sender, DayEndingEventArgs e)
{
if (IsHooked) OnDayEndingImpl(sender, e);
}
protected abstract void OnDayEndingImpl(object? sender, DayEndingEventArgs e);
}

此模式确保实现仅在事件"hooked"时运行,这允许应用程序的其他部分通过从Event基类调用HookUnhook方法来激活/取消激活事件。

internal abstract class Event
{
public bool IsHooked {get; private set;}
public bool Hook() => !IsHooked && (IsHooked = true);
public bool Unhook() => IsHooked && !(IsHooked = false);
}

(Event显然比这更复杂,但这足以了解情况)。我的EventManager可以实例化此模式的每个实现之一,并将它们的OnDayEnding与外部API中的适当处理程序挂钩。

这在一段时间内工作得很好,但现在我有一个新的需求来为这些类添加优先级。这样做的唯一方法(这是外部API的限制)是将属性[EventPriority]添加到事件回调中。但显然我不能用优先级注释OnDayEnding,因为这会设置所有实现的优先级,从而破坏了整个目的。

该属性除了对回调函数没有任何作用。我能看到的唯一其他解决方案是删除Impl,只是使回调本身抽象。但这意味着我必须在每个实现上手动检查IsHooked标志,这是我想要避免的。

所以问题是,谁能建议一个替代这个模式,将允许我有回调的不同实现,我可以添加优先级属性,和2)强制检查IsHooked?

当我最近遇到类似的问题时,有两种可能:

选项一,有一个具有所需属性的入口方法:

public class SpecificImplementationClass1 : BaseClass, IInitializer 
{
[SomeAttribute]
public void CallMeToInitiate(SomeType input)
{
ExecuteCommonCode(input);
}
protected override void ExecuteSpecificCode(object input)
{
var typedInput = (SomeType) input;
// ...execute whatever implementation-specific code here
}
}
public class BaseClass
{
protected void ExecuteCommonCode(object input)
{
// DoSomethingBefore(input);
ExecuteSpecificCode(input);
// DoSomethingAfter(input);
}
protected abstract void ExecuteSpecificCode(object input);
}
public interface IInitializer
{
void CallMeToInitialize(SomeType input);
}
// Get all IInitializers through dependency injection and call "CallMeToInitialize(new SomeType())" on each

选项二,使用模板委托模式

最新更新