Chain of Responsibility by Brian Carper, Christophe Grand, Chas Emerick

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Chain of Responsibility

While Clojure’s facilities make many patterns unnecessary or invisible, a select few remain relevant and continue to impact our design and implementation of Clojure programs. One of these is a common form of flow control called chain of responsibility. In this pattern, an event is sent off to be processed by some set handlers. A handler can process the event or pass the event on to another processing handler. These handlers form a chain, and the event is passed down the chain until one of the handlers determines that the event should not be propagated further.

Chain of command is useful because it allows a process to be defined in multiple parts that can be composed and combined. No step needs to know anything about other steps in the process, other than how to pass control down the chain.

This concept shows up in many areas. Unix pipes are an example where textual data is passed from process to process. Filters on Java Servlets are another, where web requests are passed through a series of filters until or before a response is generated.

In Java, a chain of responsibility can be constructed by defining a series of “processor” objects and then initializing each with a pointer to the next processor.

abstract class Processor { protected Processor next; public addToChain(Processor p) { next = p; } public runChain(data) { Boolean continue = this.process(data); if(continue and next != null) { next.runChain(data); } } abstract public boolean process(String data); } ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required