事件,委托或接口? [英] Event, delegate or interface?

查看:108
本文介绍了事件,委托或接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 Monkey 类,有时需要获取香蕉的实例。这种香蕉提供的方式对猴子来说并不感兴趣,但它确实启动了香蕉的采集。

Suppose I have a Monkey class which sometimes needs to acquire an instance of Banana. The way this banana is provided is not of interest to the monkey, but it does initiate the banana acquisition.

现在我至少有三种可能的方式将我的猴子连接到一个香蕉供应商。 最好的方法是什么?

Now I have at least three possible ways to wire my monkey to a banana provider. What is the best way to do it?

1。事件

提高一个 Monkey.BananaNeeded 事件。事件处理程序设置 BananaNeededEventArgs.Banana 属性。

Raise a Monkey.BananaNeeded event. The event handler sets the BananaNeededEventArgs.Banana property.

2。界面

调用 IBananaProvider.GetBanana IBananaProvider 实例作为构造函数或通过属性注入到猴子中。

Invoke IBananaProvider.GetBanana. The IBananaProvider instance is injected in the monkey as a constructor argument or through a property.

3。委派

调用类型为 System.Func< Banana和GT; 。代理人作为构造函数或通过属性注入到猴子中。这个是诱人的,因为它不需要声明任何额外的接口或类,但显然不是一个受欢迎的选择。

Invoke a delegate of type System.Func<Banana>. The delegate is injected in the monkey as a constructor argument or through a property. This one is tempting because it doesn't require the declaration of any extra interfaces or classes, but apparently it is not a popular choice.

推荐答案

我不喜欢事件和委托选项,除非有机制来确保不会附加多个处理程序。因此,方案2是获胜者,IMO。

I don't like the event and delegate options unless there is a mechanism to ensure multiple handlers won't be attached. Option 2 is therefore the winner, IMO.

这篇关于事件,委托或接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆