通过C#事件实现模板方法模式是一个好习惯吗?

时间:2022-02-10 21:06:49

I am now trying to understand some code and I have found a pattern, which seem a bit strange to me. There is a user's control class with 'EditorOpen' event. At first, I thought this name is incorrect, because it does not end with '-ing' or '-ed', as MSDN suggests. However, later I have found out, that this event does not INFORM about something happening, but it is rather some kind of REQUEST to do the actual operation. This is the client code, which is expected to perform the "opening of the editor"!

我现在正在尝试理解一些代码,我发现了一个模式,这对我来说有点奇怪。有一个带有'EditorOpen'事件的用户控件类。起初,我认为这个名称是不正确的,因为它不会以'-ing'或'-ed'结尾,正如MSDN建议的那样。然而,后来我发现,这个事件并没有发生关于发生事情的信息,但它实际上是某种REQUEST来进行实际操作。这是客户端代码,有望执行“打开编辑器”!

I was a bit surprised to find out that this is actually some form of Template Method Design Pattern, in which there can be multiple actions connected with a single action placeholder.

我有点惊讶地发现这实际上是某种形式的模板方法设计模式,其中可以有多个动作与单个动作占位符相关联。

I think it is quite interesting, but I am also afraid that using events in such cases may be highly misleading. Anyway, we are not talking about EVENTS here, but about REQUESTS. Hm... maybe it would be ok, if only the name of the event was 'EditorOpeningRequest' or 'EditorOpeningRequested'. What do you think? How would you comment this during a code review?

我认为这很有意思,但我也害怕在这种情况下使用事件可能会产生很大的误导。无论如何,我们不是在讨论EVENTS,而是关于REQUESTS。嗯...也许没关系,只要事件的名称是'EditorOpeningRequest'或'EditorOpeningRequested'。你怎么看?您在代码审查期间如何评论这一点?

1 个解决方案

#1


Unless there is a very good reason for you to have multiple objects handling a request for opening an editor, I would suggest that should be a delegate instead of an event. This restricts you to having one handler of the request, which in this case seems more logical.

除非你有很好的理由让多个对象处理打开编辑器的请求,否则我建议应该是委托而不是事件。这限制了您拥有一个请求处理程序,在这种情况下似乎更合乎逻辑。

Further more I would change the name to OpenEditor as this is more descriptive as to what you're going to expect. If you do stick with the event model, then OpenEditorRequested may be a better name.

我还会将名称更改为OpenEditor,因为这更符合您的期望。如果您坚持使用事件模型,那么OpenEditorRequested可能是一个更好的名称。

HTH.

#1


Unless there is a very good reason for you to have multiple objects handling a request for opening an editor, I would suggest that should be a delegate instead of an event. This restricts you to having one handler of the request, which in this case seems more logical.

除非你有很好的理由让多个对象处理打开编辑器的请求,否则我建议应该是委托而不是事件。这限制了您拥有一个请求处理程序,在这种情况下似乎更合乎逻辑。

Further more I would change the name to OpenEditor as this is more descriptive as to what you're going to expect. If you do stick with the event model, then OpenEditorRequested may be a better name.

我还会将名称更改为OpenEditor,因为这更符合您的期望。如果您坚持使用事件模型,那么OpenEditorRequested可能是一个更好的名称。

HTH.