通过 C# 事件实现模板方法模式是一个好习惯吗?
我现在试图理解一些代码,并且发现了一种模式,这对我来说似乎有点奇怪。 有一个带有“EditorOpen”事件的用户控件类。 起初,我认为这个名称不正确,因为它不像 MSDN 所建议的那样以“-ing”或“-ed”结尾。 然而,后来我发现,这个事件并不通知发生的事情,而是某种进行实际操作的请求。 这是客户端代码,预计将执行“打开编辑器”!
我有点惊讶地发现这实际上是某种形式的模板方法设计模式,其中可以有多个操作与单个操作占位符连接。
我认为这很有趣,但我也担心在这种情况下使用事件可能会产生很大的误导。 不管怎样,我们这里讨论的不是事件,而是请求。 嗯...如果事件的名称是“EditorOpeningRequest”或“EditorOpeningRequested”,也许就可以了。 你怎么认为? 在代码审查期间您会如何评论这一点?
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"!
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非有充分的理由让您有多个对象处理打开编辑器的请求,否则我建议应该使用委托而不是事件。 这限制了您只能拥有一个请求处理程序,在这种情况下这似乎更合乎逻辑。
此外,我会将名称更改为 OpenEditor,因为这更能描述您所期望的内容。 如果您坚持使用事件模型,那么 OpenEditorRequested 可能是一个更好的名称。
HTH。
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.
HTH.