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.
Have you ever done the design of a layered application – usually representing a certain functional domain or microservice – consisting of the usual Web-, Façade-, Businesslogic- and Data-Access-Layers? Did that annoy you because of the continuously rising quantity of pure delegation methods in the Façade- and Businesslogic-Layer that produce nothing but “hot air” (and of course work overhead)? Then the CDI-based “Enhanced Eventdriven Service-Design” (“EESD”) is for you!
In this first part of my upcoming series I’d like to show you a new way of implementing the “factory-method” pattern. To be more precise, it is what the famous “Gang-of-Four” call a “parameterized factory-method” in the Design Patterns-Book (see the “Implementation” section of the “Factory Method Pattern” on page 110/111). For simplicity I will use the term “factory-method” synonym to “parameterized factory-method”. The crucial point here will be, that the factory no longer needs any compile-time dependencies upon any concrete interface implementation. Furthermore I will explain how to write un-mocked unit-tests for a CDI-Bean (the factory) in order to be able to check that all the CDI annotations work as desired without having to start an application server.