Chain of Responsibility

Intent

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Structure of design pattern

Chain Of Responsibility pattern structure

Pseudocode

// Abstract handler interface.
abstract class Component is
    field onClick: function

    // Basic handling method. It will be called when no other handler is capable
    // of processing a click.
    method click(x, y) is
        if (onClick != null)
            onClick(context)

    abstract method render(x, y, width, height)


// Concrete component implementation. It inherits basic functionality from the
// abstract handler.
class ContainerComponent extends Component is
    // Complex concrete component, which has references to other components.
    field children: array of Component

    method add(child) is
        children.add(child)

    // Component stores its references here.
    method click(x, y) is
        if (onClick != null) then
            onClick(context)
        else if (child.atCoord(x,y))
            child.click(x, y)


// If can't handle a click yourself, then pass it to your child component if you
// have one at a click's coordinate.
class Button extends Component is
    method render() is
        Draw a button.

class Panel extends ContainerComponent is
    method render() is
        Draw a panel and its children.


// Client code.
class Application is
    // Each application configures the chain differently.
    method createUI() is
        panel = new Panel(0, 0, 400, 800)
        ok = new Button(250, 760, 50, 20, "OK")
        ok.onClick({ ... })
        panel.add(ok);
        cancel = new Button(320, 760, 50, 20, "Cancel")
        cancel.onClick({ ... })
        panel.add(cancel)

    // Imagine what happens here.
    method test() is
        panel.click(251, 761)

Implementations in Different Programming Languages

Java