This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging
First of all, clarify the meaning
- Chain of responsibility pattern: A chain of receiver objects is created for the request. This pattern gives the type of request, decouples the sender and receiver of the request, and belongs to the behavioral pattern.
- In this pattern, usually each receiver contains a reference to another receiver. If an object cannot handle the request, it passes the same request to the next recipient, and so on.
The scenarios we use in our work
- For example, we have a practical OA company approval system, such as in the reimbursement bill or approval system
- In our case, BOOS has the absolute right of approval, followed by the second review of finance and the first review of department head
- So the intuitive way to think about business logic is
if (leader.author ! = null) { if (financialer.author ! = null) { if (boss.author ! = null){ handle(...) }}}Copy the code
-
Take a closer look at the chain of responsibility pattern with the following example
-
Example: the teacher can view the student’s family information, monitor can only view the student’s native place information, and league branch secretary can only view the student’s league membership
-
The enforcement rights of each layer can be linked down
-
Create an abstract class abstractAuther with detailed levels of responsibility
- Create the teacher class
- Creating the Monitor class
- Create league branch secretary class
- Create different levels of roles and give them different levels of responsibility
- Final output
You can view the student's family information ------ Family information details you can view the student's family information ------ Home place information details you can view the student's home place information ------ Home place information details you can view the student's family information ------ Team building information details you can view the student's home place information ------ team building information details You can view the student's league membership at ------Copy the code
- The responsibilities of each role can be passed down or across levels
features
- The main solution: the handler on the chain of responsibility is responsible for processing the request, and the user only needs to send the request to the chain of responsibility. The user does not need to care about the processing details of the request and the delivery of the request, so the chain of responsibility decouple the sender of the request and the handler of the request.
- Advantages: Â
- Reduce coupling. It decouples the sender and receiver of the request.
- Simplified objects. So that the object does not need to know the chain structure.
- Disadvantages: Â
- There is no guarantee that the request will be received.
- System performance will suffer, and it will be inconvenient to debug your code and may cause looping calls.