It's a design pattern to cascade a task across a series of objects. The purpose can be finding the object that can solve a problem or can be processing the same data through a different number of algorithms.
Chain of responsability favour loose coupling. It is normally used when more than one object can handle a request.
Here's an example for a hypothetical server with multiple processors. It will check the first available processor to handle data.
import java.util.Random; /** * Processor with basic functionality for chain of responsability. */ public abstract class Processor { protected Processor next; public void setNext(Processor next) { this.next = next; } public void process(String data) { execute(data); } protected boolean checkIfFree() { // For this demo the check is a random check return new Random().nextInt(2) == 0; } protected abstract void execute(String data); protected void goNext(String data) { if (next!= null) next.execute(data); else System.out.println("No processor available"); } } /** * First processor to be checked, if not available switch * to processor B */ public class ProcessorA extends Processor { @Override protected void execute(String data) { if (checkIfFree()) { System.out.println("Processing with A"); } else { goNext(data); } } } /** * Second processor, if not available switch * to processor C */ public class ProcessorB extends Processor { @Override protected void execute(String data) { if (checkIfFree()) { System.out.println("Processing with B"); } else { goNext(data); } } } /** * third processor, if not available no other processor * is available for the machine. */ public class ProcessorC extends Processor { @Override protected void execute(String data) { if (checkIfFree()) { System.out.println("Processing with C"); } else { goNext(data); } } } /** * Demonstrates the chain of responsability design pattern */ public class App { public static void main(String[] args) { // Create three processors Processor mainProcessor = new ProcessorA(); Processor secondProcessor = new ProcessorB(); Processor thirdProcessor = new ProcessorC(); // Set the chain of responsability mainProcessor.setNext(secondProcessor); secondProcessor.setNext(thirdProcessor); // Check the processor available and run it mainProcessor.execute("any data here"); } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.