“Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.” From refactoring Guru.“Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.”
From refactoring Guru.
Example
Imagine that you have several processes to carry out and that share common components, but they must follow sequential steps and share the resulting data.
- All processes first validate users and tokens. If correct, continue
- All processes validate a photograph parameter.
- Data must be passed between processes.
The main idea is to create an example of a chain of responsibility.
Step 1. Create a folder "Chain" and four classes.
Handle Base is the logic for an abstract class. Work as a base for other handlers. The method SetNext is used to set the next handler in the chain.
IHandler is the implementation of the Handle base.
HandleFactory, in this class, we create different chain handlers and implement the necessary methods to work.
Processor. In this class work with the setup of chains, the dictionary _handlerchains is for storing the different handlers in the app.
Step 2. Create folder "Classes"
in this folder are the different classes of project; RequestBase for initial validation, DataReniec is an example of getting data from an external site, requestPic for validating pictures
Step 3. The ExampleBase.
In this folder, the class ProcessRequest is used to set the class for use in handlers, the data to share between handlers, and the state of handlers.
Step 4. Functions.
in this folder, I put some classes in order to simulate more complex elements for the chains, make validations, and simulate internal data result
Step 5. Handlers.
In this folder, I did every handler extend for the abstract class handler base, validated data, and set handler result and data handler result consuming in the next handler example.
Last Step
For the program, in this example, I set up the request for "ProcessSavePicReniec", set the initial data, and executed the program.
You can download the project.
Github