Alex Rivera | Logout

Event, delegate or interface?

Asked 2009-08-19T13:25:54.287
26

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. Event

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

2. Interface

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

3. Delegate

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.

c#
Edit
Report

1 Answer

4

The event model works best if there is several possible banana providers, i.e. the monkey asks all providers in turn for a banana, and the first one that can provide one gets to deliver it.

The other two models work fine for a single banana prover per monkey. The delegate is easier to create a provider for, and the interface is more structured.

answered 2009-08-19T13:33:55.420

Your Answer