The intend of Chain of Responibility Pattern is to avoid coupling the sender of a request to its reciever by giving more than one object change to handle the request.
Let’s try to mimic the execution of classical Waterfall Model with CoR. Let’s begin by declaring the contract interface.
public interface IWaterfall { void Execute(); IWaterfall NextStage { get; set; } }
And our sub classes.
internal class Requirements : IWaterfall { public IWaterfall NextStage {get;set;} public void Execute() { Console.WriteLine(nameof(Requirements)); if (NextStage is IWaterfall) NextStage.Execute(); } } internal class Design : IWaterfall { public IWaterfall NextStage { get; set; } public void Execute() { Console.WriteLine(nameof(Design)); if (NextStage is IWaterfall) NextStage.Execute(); } } internal class Implementation : IWaterfall { public IWaterfall NextStage { get; set; } public void Execute() { Console.WriteLine(nameof(Implementation)); if (NextStage is IWaterfall) NextStage.Execute(); } } internal class Verification : IWaterfall { public IWaterfall NextStage { get; set; } public void Execute() { Console.WriteLine(nameof(Verification)); if (NextStage is IWaterfall) NextStage.Execute(); } } internal class Deployment : IWaterfall { public IWaterfall NextStage { get; set; } public void Execute() { Console.WriteLine(nameof(Deployment)); if (NextStage is IWaterfall) NextStage.Execute(); } } internal class Maintenance : IWaterfall { public IWaterfall NextStage { get; set; } public void Execute() { Console.WriteLine(nameof(Maintenance)); if (NextStage is IWaterfall) NextStage.Execute(); } }
The final step is link up the chain and get the execution rolling from client.
IWaterfall Handler1 = new Requirements(); IWaterfall Handler2 = new Design(); IWaterfall Handler3 = new Implementation(); IWaterfall Handler4 = new Verification(); IWaterfall Handler5 = new Deployment(); IWaterfall Handler6 = new Maintenance(); Handler1.NextStage = Handler2; Handler2.NextStage = Handler3; Handler3.NextStage = Handler4; Handler4.NextStage = Handler5; Handler5.NextStage = Handler6; Handler1.Execute();
As you can see the responsibility is handled by the chain of classes, each executing a single responsibility (following Single Responsibility Principle). Also, the functionality can be extended by further linking up the chain, thereby satisfying the Open-Closed Principle.
Code samples can be found here. Complete list of Patterns and Principles could be found here.
Need more real life example.
Could add passing DTO/object
DI 3rd party services into handlers,
Skip step,
etc.
LikeLike
Thank You Leszek. Yes, thats a good suggestion. Will include more real life example.
LikeLike