Chain of responsibility pattern comes under Behavioral design pattern.
It lets more than one receiver handler to process the request and
decouples the sender of request to its receiver.
Behaviour & Advantages
Chains the receiving objects and passes request through chain until its handled by a receiver.
The receiver is determined based on request data.
The receiver takes the responsibility of delegating to next receiver in chain if it cannot process the request.
Decouples the sender of request to its receiver.
This example shows a Travel suggest where user inputs the distance to travel.
Travel suggest outputs best travel means for the distance given.
Interface ITravelHandler acts as Handler and
classes Walk, Bus, Train, Airplane & Rocket acts as ConcreteHandlers or Receivers
which can be chained together by TravelSuggest class.
/**
* Process the travel data
*/ public void processHandler(TravelData travelData);
/**
* Set next handler in the chain
*/ public void setNextHandler(ITravelHandler travelHandler);
/**
* Get next handler in the chain
*/ public ITravelHandler getNextHandler();
}
We can see that there is min and mix limit on distance to be processed by each receiver handler.
If the current handler cannot process the travel data, it will delegate the request processing to
next handler in the chain.
The abstract and concrete implementations of handlers are shown below,
TravelData travelData = new TravelData(4);
travelSuggest.suggest(travelData);
travelData = new TravelData(12);
travelSuggest.suggest(travelData);
travelData = new TravelData(56);
travelSuggest.suggest(travelData);
travelData = new TravelData(968);
travelSuggest.suggest(travelData);
travelData = new TravelData(6789);
travelSuggest.suggest(travelData);
travelData = new TravelData(-1);
travelSuggest.suggest(travelData);
}
}
It gives the following output,
INTROSPECT : Walk[0-5] < Bus[5-20] <
Train[20-100] < Airplane[100-1000] < Rocket[1000-2147483647]
Best choice for distance (4KM) is 'Walk'
Best choice for distance (12KM) is 'Bus'
Best choice for distance (56KM) is 'Train'
Best choice for distance (968KM) is 'Airplane'
Best choice for distance (6789KM) is 'Rocket'
Couldn't process travel data.