模式 / 行为模式
image

//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