How to notify event subscriber
In my last job interview I was asked how to implement a class which exposes an event and notifies new event subscribers at the moment they subscribe to that event.
In other words, a class exposes an event to inform subscribers when a data source is updated; many other classes can subscribe to the event at any point in time. When a class subscribes to the event it must be notified to get latest version of data stored into the data source, but other classes must not be notified (they are already up to date).
They have suggested me to override the addHandler method, but how do I notify only the new subscriber?
Is there a feature of the .net I'm not aware of or do I need to define a method in the subscriber class to be called when adding to handler (some kind observer pattern)?
EDIT: i think i'm not been clear, so i'll try to explain it in another way. Suppose i've an observer pattern. When a new observer subscribe the subject it gets immediatly updated with lastest datasource values by subject .Later, when somethnig inside the datasource will change, the subject will notify all registered observers as 开发者_如何学Pythonusual. I'm been asked how to make this with .net events
Your terminology is wooly - what do you mean by "it must be activated"? Do you mean the event handler has to be called once at the point of subscription? If so, that sounds something like:
private EventHandler foo;
public event EventHandler Foo
{
add
{
if (value != null)
{
value(this, EventArgs.Empty);
}
foo += value;
}
remove
{
foo -= value;
}
}
It's a pretty odd design though.
If that isn't what you're after, please try to clarify.
See my article on events and delegates for more information.
精彩评论