Thursday 30 November 2017

Chain of Responsibility Design Pattern


Motivation
In writing an application of any kind, it often happens that the event generated by one object needs to be handled by another one. And, to make our work even harder, we also happen to be denied access to the object which needs to handle the event. In this case there are two possibilities: there is the beginner/lazy approach of making everything public, creating reference to every object and continuing from there and then there is the expert approach of using the Chain of Responsibility.
The Chain of Responsibility design pattern allows an object to send a command without knowing what object will receive and handle it. The request is sent from one object to another making them parts of a chain and each object in this chain can handle the command, pass it on or do both. The most usual example of a machine using the Chain of Responsibility is the vending machine coin slot: rather than having a slot for each type of coin, the machine has only one slot for all of them. The dropped coin is routed to the appropriate storage place that is determined by the receiver of the command.

Intent
It avoids attaching the sender of a request to its receiver, giving this way other objects the possibility of handling the request too.
The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it.

Applicability
Use Chain of Responsibility when
1. more than one object may handle a request, and the handler isn't known a prior. The handler should be ascertained automatically.
2. you want to issue a request to one of several objects without specifying the receiver explicitly.
3. the set of objects that can handle a request should be specified dynamically.

Benefit(s)
1. Reduced coupling.
2. Added flexibility in assigning responsibilities to objects.

Disadvantage(s)
1. Receipt isn't guaranteed.

Happy Learning.

1 comment: