The chain of responsibility pattern is defined to avoid coupling between the sender and receiver of the request by giving multiple objects the opportunity to process the request, linking the object into a chain, and passing the request along the chain until one object processes it. I won’t talk too much about the chain of responsibility pattern here, but mainly about how to write it in Java. This is mainly introduced from the code in the following three frameworks.

The servlet filter

The filter of dubbo

The plugin mybatis

The servlet Filter

Servlet defines a Filter and FilterChain interface respectively, the core code is as follows:


The code is relatively simple, the structure is also relatively clear, define a Chain, which contains the Filter list and servlet, to achieve a variety of Filter logic before calling the real servlet.




The Filter of Dubbo

Dubbo is another method to create a Filter. It encapsulates the Filter as an anonymous class of Invoker and completes the chain of responsibility through a data structure such as a linked list. The core code is as follows:


Dubbo’s responsibility chain does not have a class like FilterChain. Instead, it creates a linked list that only knows the first node at the time of the call. Each node contains the information of the next node. Although the Invoker wrapper Filter does not specify next explicitly, the same effect is achieved through Java anonymous classes and final mechanisms.




The Plugin Mybatis

Mybatis can be configured with a variety of plugins, whether officially provided or self-defined, Plugin and Filter are similar, in the execution of Sql statements to do some operations. The chain of responsibility for Mybatis is dynamically proxying the actual Executor class using the Plugin. (The composite pattern is actually used here, because plugins can nest agents), the core code is as follows:


Here’s a simple diagram:


conclusion

Servlet, Dubbo and Mybatis are introduced in this paper. Among them, Servlet is relatively clear and easy to implement, while Dubbo and Mybatis are suitable for adding the responsibility chain mode code on the basis of the original code with the smallest change. https://dwz.cn/1TtgW7Ud