Chain of Responsibility Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the chain of responsibility pattern, a behavioral object pattern.
Tutorial created using: Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


Page: < 1 2

(Continued from page 1)

EarthHandler similarly handles PlanetEnum.EARTH requests.

EarthHandler.java

package com.cakes;

public class EarthHandler extends PlanetHandler {

	public void handleRequest(PlanetEnum request) {
		if (request == PlanetEnum.EARTH) {
			System.out.println("EarthHandler handles " + request);
			System.out.println("Earth is comfortable.\n");
		} else {
			System.out.println("EarthHandler doesn't handle " + request);
			if (successor != null) {
				successor.handleRequest(request);
			}
		}
	}

}

The Demo class is the client class. It creates the chain of handlers, starting with MercuryHandler, then VenusHandler, and then EarthHandler. The setUpChain() method returns the chain to main() via a PlanetHandler reference. Four requests are made of the chain, where the requests are VENUS, MERCURY, EARTH, and JUPITER.

Demo.java

package com.cakes;

public class Demo {

	public static void main(String[] args) {
		PlanetHandler chain = setUpChain();

		chain.handleRequest(PlanetEnum.VENUS);
		chain.handleRequest(PlanetEnum.MERCURY);
		chain.handleRequest(PlanetEnum.EARTH);
		chain.handleRequest(PlanetEnum.JUPITER);
	}

	public static PlanetHandler setUpChain() {
		PlanetHandler mercuryHandler = new MercuryHandler();
		PlanetHandler venusHandler = new VenusHandler();
		PlanetHandler earthHandler = new EarthHandler();

		mercuryHandler.setSuccessor(venusHandler);
		venusHandler.setSuccessor(earthHandler);

		return mercuryHandler;
	}

}

The console output of the execution of Demo is shown here. Notice that if a handler can't handle the request, it passes the request on to the next handler.

Console Output

MercuryHandler doesn't handle VENUS
VenusHandler handles VENUS
Venus is poisonous.

MercuryHandler handles MERCURY
Mercury is hot.

MercuryHandler doesn't handle EARTH
VenusHandler doesn't handle EARTH
EarthHandler handles EARTH
Earth is comfortable.

MercuryHandler doesn't handle JUPITER
VenusHandler doesn't handle JUPITER
EarthHandler doesn't handle JUPITER

Notice that the last request made of the chain is JUPITER. This request is not handled by any handlers, demonstrating that a request does not have to be handled by any handlers. If we had wanted to, we could have also written an OtherPlanets handler and placed it at the end of the chain to handle planet requests not handled by other previous handlers. This would demonstrate that we can make our handlers specific at the beginning of the chain and more general at the end of the chain, thus handling broader categories of requests as we approach the end of the chain.

Page: < 1 2


Related Tutorials: