
//Handler
abstract class Rescuer {
protected Rescuer next;
protected int code;
//HandleRequest()
void help(int code) {
if (this.code == code) {
toHelp();
} else if (next != null) {
next.help(code);
}
}
abstract void toHelp();
}
//ConcreteHandler
class Firefighter extends Rescuer {
public Firefighter(Rescuer next) {
this.next = next;
this.code = 1;
}
protected void toHelp() {
System.out.println("call firefighters");
}
}
//ConcreteHandler
class Police extends Rescuer {
public Police(Rescuer next) {
this.next = next;
this.code = 2;
}
protected void toHelp() {
System.out.println("call the police");
}
}
//ConcreteHandler
class Ambulance extends Rescuer {
public Ambulance(Rescuer next) {
this.next = next;
this.code = 3;
}
protected void toHelp() {
System.out.println("call an ambulance");
}
}
var ambulance = new Ambulance(null);
var police = new Police(ambulance);
var firefighter = new Firefighter(police);
firefighter.help(1);
//printed: call firefighters
firefighter.help(2);
//printed: call the police
firefighter.help(3);
//printed: call an ambulance
| 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. |