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

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

问题描述

假设我有一个猴子类,它有时需要收购的香蕉的实例。提供这种香蕉的方法是不感兴趣的猴子,但它引发的香蕉收购。

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是赢家,海事组织。

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天全站免登陆