Chain of Responsibility


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


// 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)

    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

    // Component stores its references here.
    method click(x, y) is
        if (onClick != null) then
        else if (child.atCoord(x,y))
  , 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({ ... })
        cancel = new Button(320, 760, 50, 20, "Cancel")
        cancel.onClick({ ... })

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

Implementations in Different Programming Languages