Most of us know design patterns, and most of us know Chain of Responsibility.
In my opinion this is a very useful pattern, but a lot of the implementation found online, have this feeling of oldness upon them.
The text book example is something like:
To me this seems old school. Sure it works, it's readable and well documented, but wouldn't you like something more like this instead?
At least I like it much better, and that is the most important :)
So how is this implemented? Well it is pretty straightforward, it consists of:
- ChainElement<TOutput> which contains the result and whether it was handled or not.
- IChain<TInput, TOutput> which is an interface defining a single part of the chain.
- ChainExtensions which contains extension methods for chaining.
The whole implementation can be seen below:
The magic happens in the extension methods, it basically allows you to build a list and feed it an input until it's handled.
A handler could be implemented like this:By: Kim Christensen