Chain of Responsibility Pattern
Chain of responsibility pattern consist source of command objects and chains of processing objects. Here all individual processing objects will be containing the logic that defines what types of command objects it could handle and after filtering out commands rest will be passed to next processing object in series. In the last mechanism will be applied to add new processing objects.
In deviation of standard chain of responsibility pattern model some of the handlers could act as dispatchers and capable to send commands in variety of directions which forms tree of responsibility. In some of the scenario it could occurs recursively with the processing objects calls higher processing objects using commands which will attempt to solve smaller part of problem and this case recursion will be continue until the last command has processed or in another words until entire tree been explored. Best example is XML interpreter which works in this manner. It promotes idea of loose coupling which is known as very good programming practice.
Below code showing pattern with example of logging class. Here log handler decides if any action should take at this logger level and once done pass message to next logging handler.
Also please take note here that when you do actual implementation of chain of responsibility pattern logger will not pass responsibility further down to chain after handling message. Our example message will be passing down to chain whether it handled or not.
- Create abstract class Logger:
- Create class StdoutLogger and extends Logger
- Create class EmailLogger and extends Logger
- Create class StderrLoggerand extends Logger
- Create test class chainOfResponsibilty
- That’s it. Below is list of all design patterns link:
- Chain of Responsibility
- Template Method