user310291
user310291

Reputation: 38220

What advantages does it bring to use C# event system to implement Publisher/Subscriber pattern instead of implementing it with class interfaces?

There is an implementation shown here: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx

What's the advantages over just implementing this design pattern the classical way with class interfaces ?

For example where is the decoupling since you have tight direct binding between the subscribers and the publisher through the instruction:

pub.RaiseCustomEvent += HandleCustomEvent;

So that in this case I can't see any decoupling advantage over direct classical implementation.

Upvotes: 1

Views: 719

Answers (2)

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

Again, convenience:

With interfaces, you have to:

  • derive from interface
  • implement callbacks (all of them!), even if you don't need some event
  • register

With events, everything is done in one line, and .NET automatically handles multiple hooks to one event.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1063328

Convenience is a biggie, especially since C# doesn't have the inner classes of Java; since it would be a single-method interface, this allows trivial subscription - perhaps via a method on the type, but perhaps even inline:

pub.RaiseCustomEvent += delegate { DoSomething(); };

The above also allows for full lexical capture of any variables etc (contrast with Java, which captures the values of any variables - not the variables themselves - so 2-way communication is possible).

To do this with an interface I would need to declare a new class, implement the interface, provide a method to provied the implementation, and handle any variable/capture transfer.

Events also allow broadcast to multiple subscribers in a very convenient way.

Delegates are also easier to create at runtime (for meta-programming etc) than classes are - for example I can create a delegate (from scratch) at runtime and subscribe it pretty easily, using either DynamicMethod (if I fancy IL) or Expression (if I fancy AST). To create a type and implement an interface is a bit more work (AssemblyName, AssemblyBuilder, ModuleBuilder, TypeBuilder and at least 2 Types and MethodInfos).

Upvotes: 2

Related Questions