According to the GOF’s definition:
“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”
This is how Chain of responsibility
works:
1. The base class maintains a “next” pointer.
2. Each derived class implements its contribution for handling the request
3. If the request is not able to be processed by the class then it delegates to the “next” pointer of the base class and so it goes on.
4. The client forms the order/links the chain.
1. The base class maintains a “next” pointer.
2. Each derived class implements its contribution for handling the request
3. If the request is not able to be processed by the class then it delegates to the “next” pointer of the base class and so it goes on.
4. The client forms the order/links the chain.
Chain of
Responsibility simplifies object interconnections. Instead of senders and
receivers maintaining references to all candidate receivers, each sender keeps
a single reference to the head of the chain, and each receiver keeps a single
reference to its immediate successor in the chain.
Do not
use Chain of Responsibility when each request is only handled by one handler,
or, when the client object knows which service object should handle the request.
Example:
Consider a
leave management system, If you applying for not more than 5 leaves then
directly your reporting manager can approve it, if it is more than 5 then he
will decline it and you have to again move the request to Program manager, instead
you moving the request, the reporting manager can directly delegate to Program
manager and Program manager to Management and so on.
Handler:
An interface or abstract class which contains the “next” handler.
[Code]
Concrete
handler: Actual request handlers
[Code]
Client:
The employee who request for leave
[Code]
UML:
Examples:
1. ATM machine
2. Leave management system
1. ATM machine
2. Leave management system
References:
1.
https://sourcemaking.com/design_patterns/chain_of_responsibility
2.
http://www.dotnettricks.com/learn/designpatterns/chain-of-responsibility-design-pattern-dotnet
3.
https://dotnetfreakblog.wordpress.com/2013/09/16/chain-of-responsibility-design-pattern/
No comments:
Post a Comment