Chain of Responsibility Pattern

23
Object Behavioral Pattern

description

A Brief Presentation about Chain of Responsibility Pattern based on GoF Design Patterns Book

Transcript of Chain of Responsibility Pattern

Page 1: Chain of Responsibility Pattern

Object Behavioral Pattern

Page 2: Chain of Responsibility Pattern

2

Motivation Ever tried [email protected] A central starting point for UA members to get

help about all subjects. You can ask questions about many things

(academic, registrar, actioncard, IT…) Your question will be solved by the related

department and a reply will be sent. That means you can ask a question, and do

not care which department will answer it. You just need the answer, and you will get it.

Page 3: Chain of Responsibility Pattern

3

Intuitive Solution There will be a manager, who receives all

mails those are sent to [email protected] The manager will process every mail and

redirects it to the appropriate department. In this case, the manager must have

references to all departments.

Page 4: Chain of Responsibility Pattern

4

An Efficient Solution You send the mail to [email protected] Your mail will be forwarded to the first

department to be answered. If that department do not have the answer, it

will forward the mail to next department. Forward chain will go on until a department

will answer your question.

Page 5: Chain of Responsibility Pattern

5

Chain of Responsibility Pattern Avoid coupling the sender of a request to its

receiver by giving more than one object to handle the request.

Chain the receiving objects and pass the request along the chain until an object handles it.

Page 6: Chain of Responsibility Pattern

6

Participants Handler

Defines the interface for handling requests Can implement the successor link

Concrete Handler Handles requests it is responsible for Can access its successor If can handle request, it does so; else forwards the

request to its successor Client

Initiates the request to a ConcreteHandler object on the chain.

Page 7: Chain of Responsibility Pattern

7

Collaboration In this sequence diagram, two requests are

sent to c1 and one is replied by c2, other one is replied by c3. We can see request is passed from one another in chain.

Page 8: Chain of Responsibility Pattern

8

Consequences Reduced Coupling:

The sender does not know which other object will handle the request.

It only has to know that the request will be handled appropriately.

A request in the chain also does not have any info about the chain structure.

Flexibility The chain structure and the responsibilities of

chain members can be modified at run time (Adding new handlers etc.)

Page 9: Chain of Responsibility Pattern

9

Consequences – cont’d Receipt:

Since a request is not targeting an explicit receiver, handling it is not guaranteed.

The request can pass through from all chain members without being handled and can fall off the end of chain.

The chain must be configured properly. What if two concrete handlers try to handle

the same request? An approach is introduced on next slide! What do you think?

Page 10: Chain of Responsibility Pattern

10

Request Structure If we only have one execution method for the

request, in the previous scenario (multiple handlers), one of the handlers may never handle the request!

Solution: We can have a Request class and may have many

methods inside it. (Command Pattern?) Each handler handles the request’s some part. And passes the request along the chain.

In normal version of pattern, a request is not forwarded to the other handler in the chain after processed.

But this time, it MUST be forwarded even after processed

Page 11: Chain of Responsibility Pattern

11

Implementation Issues Default handler method may be implemented

in two way: First one is: leaving the method totally abstract

that every concrete handler have to implement that function and pass the request to successor if will not handle it.

Second is: the handler method will implement the passing the request to successor, and a concrete handler will override the handler method only if it will handle a request.

PseudoCode examples of two variations on next slide!

Page 12: Chain of Responsibility Pattern

12

Default Handler Behavior

abstract class Handler { Handler successor = null; abstract void handleRequest(r);}

// a class handling the requestclass ConcHandler1 extends Handler { void handleRequest(r) { process(r); if(successor != null) successor.handleRequest(r); }}

// a class not handling the requestclass ConcHandler2 extends Handler { void handleRequest(r) { if(successor != null) successor.handleRequest(r); }}

abstract class Handler { Handler successor = null; abstract void handleRequest(r) { if(successor != null) successor.handleRequest(r); }}

// a class handling the requestclass ConcHandler1 extends Handler { void handleRequest(r) { process(r); if(successor != null) successor.handleRequest(r); }}

// a class not handling the requestclass ConcHandler2 extends Handler {}

First method Second method

Page 13: Chain of Responsibility Pattern

13

Implementation Issues – cont’d Can you see the Chain of Responsibility in the Composite

Pattern? What is different than classic Chain of Responsibility? You can just add a handle function to Component here and

you can use children link to provide the successor effect. You have to process the request in composite nodes and after

processing, you should deliver it to right child to be handled. Not a single link chain, but a tree chain!

handle(Request r)

handle(Request r)

handle(Request r)

Path of a request

Page 14: Chain of Responsibility Pattern

14

«Exception Handling» Example Exception handling uses Chain of

Responsibility pattern. When an exception occurs, the program will

start to search for a handler from the class which exception occurs through super classes.

If an appropriate handler is found in one of superclasses, ok. If not, it will be handled globally.

Class Diagram Object Diagram

Page 15: Chain of Responsibility Pattern

15

«Cache» Example Think of a processor with level 3 cache

CPU will first look up level1 cache, then level2 and then level3, at last data will be read from main memory.

Not a concrete example of the pattern, but the logic.

Page 16: Chain of Responsibility Pattern

16

«Email Handler» Example You have a big company and you are receiving

lots of email from customers. Fan emails, spams, complaints, or a request of

new location. Here’s what you have to do:

Page 17: Chain of Responsibility Pattern

17

Pipes and Filters Pattern Email handling example looks like filtering,

right? It is also an example of architechtural pattern

called Pipes and Filters. We can use this pattern to divide a larger

processing task, into a sequence of smaller and independent steps (filters) that are connected by channels (pipes).

Here is an example of order handling steps: *Receive Order 1-Decrypt the secure order 2-Authenticate customer 3-Remove duplicate orders *Process

Page 18: Chain of Responsibility Pattern

18

Non-software Example Coin sorter of a bank ATM

When we drop coin to ATM, the ATM will try to put the coin to correct location, will start trying from quarter until cent.

Page 19: Chain of Responsibility Pattern

19

Brainstorm handleRequest method always accepted ONE

request as parameter till now, how can we change it to handle a request list? What has to change? Inside the method, we will handle the appropriate

requests, remove them out from the list, and pass remaining list to successor.

What if we configure the chain wrong and started forwarding requests not from the first handler but from the third or fourth one? We can set the successor of the last handler in the

chain to the first one. But we must ensure, the request is handled or it may cause with a loop.

Page 20: Chain of Responsibility Pattern

20

Brainstorm – cont’d If each handler modifies some part of the

request (partially handles) and passes the request to successor, will it again be chain of responsibility? What do you think? I think YES.

Chain of Responsibility vs Pipes and Filters Don’t worry, you don’t have to select one of them.

Pipes and Filters is a subclass of Chain of Responsibility. (variant to be used in architectural purposes)

Page 21: Chain of Responsibility Pattern

21

Demo It is demo time! First demo is implemented by me. Second demo is totally taken from a webpage.

You can find it in references.

Page 22: Chain of Responsibility Pattern

22

Questions

Page 23: Chain of Responsibility Pattern

23

References GoF Design Patterns Book http://

www.javacamp.org/designPattern/chains.html http://www.unilim.fr/sci/wiki/_

media/cali/cpumemory.pdf Oreilly Head First: Design Patterns Book Fry of Futurama for Questions Picture http://eaipatterns.com/PipesAndFilters.html Non-Software Examples of Software Design

Patterns by Michael Duell