In this part I will show you a modernized, CDI-based version of the good old “Chain Of Responsibility” (CoR) pattern. As you will see, it is a perfect weapon if you want to design a system and write code that follows Uncle Bob’s “SOLID Principles”, especially the Open/Closed Principle, which is often one of the hardest to achieve.
The new design is based on an Interceptor that controls and performs the calls to the Chain Handlers, which have to be annotated with appropriate CDI-Qualifiers. The key difference to the usual Chain-Pattern is, that the chain handlers are not physically connected, i.e. a handler doesn’t know about any successor. Instead, the handlers are “virtually” connected by sharing a custom, Usecase-specific CDI-Qualifier, thus I would prefer to call this modernized version a “Virtual Chain Of Responsibility“.
Compared to the modernized factory-pattern, which I had shown in part 1 (see either the original post or the dzone-post), this CoR-design leads to an even more decoupled system, because you do not need to implement a factory anymore. Instead, it gets replaced by the generically implemented “ChainOfResponsibilityControllerInterceptor”. For an opensource implementation of this concept, see the section about the “magic4j-cdi-utils” library at the end of this article or visit magic4j.org.