这个模式用的不多,笔记之,病人去医院看病的例子,来自易说设计模式一书

public abstract class Doctor {
    public abstract void seeDoctor(XiaoGong xiaoGong);

    public Doctor getDoctor(){ return doctor; }

    public void setDoctor(Doctor doctor){ this.doctor = doctor; }

    private Doctor doctor;
}

 

public class NerveDoctor extends Doctor {
    public void seeDoctor(XiaoGong xiaoGong) {
        if (xiaoGong.getHead().booleanValue()) {
            System.out.println("神经科的医生看病");
        } else if (super.getDoctor() != null) {
   super.getDoctor().seeDoctor(xiaoGong);
        }
    }
}

public class SleepDoctor extends Doctor {
    public void seeDoctor(XiaoGong xiaoGong) {
        if (xiaoGong.getSleep().booleanValue()) {
            System.out.println("睡眠中心的医生看病");
        } else if (super.getDoctor() != null) {
   super.getDoctor().seeDoctor(xiaoGong);
        }
    }
}

public class AssimilationDoctor extends Doctor {
    public void seeDoctor(XiaoGong xiaoGong) {
        if (xiaoGong.getStomach().booleanValue()) {
            System.out.println("消化科的医生看病");
        } else if (super.getDoctor() != null) {
   super.getDoctor().seeDoctor(xiaoGong);
        }
    }
}

 

病人类
public class XiaoGong {
    public Boolean getSleep(){ return sleep; }

    public void setSleep(Boolean sleep){ this.sleep = sleep; }

    public Boolean getHead(){ return head; }

    public void setHead(Boolean head){ this.head = head; }

    public Boolean getStomach(){ return stomach; }

    public void setStomach(Boolean stomach){ this.stomach = stomach; }

    private Boolean sleep;
    private Boolean head;
    private Boolean stomach;
}

 

客户调用类
 XiaoGong xiaoGong = new XiaoGong();
  Doctor nerveDoctor = new NerveDoctor();
        Doctor sleepDoctor = new SleepDoctor();
        Doctor assimilationDoctor = new AssimilationDoctor();
  nerveDoctor.setDoctor(sleepDoctor);
  sleepDoctor.setDoctor(assimilationDoctor);
      xiaoGong.setHead(new Boolean(true));
  nerveDoctor.seeDoctor(xiaoGong);
        xiaoGong.setSleep(new Boolean(true));
  xiaoGong.setHead(new Boolean(false));
        nerveDoctor.seeDoctor(xiaoGong);
        xiaoGong.setStomach(new Boolean(true));
  xiaoGong.setSleep(new Boolean(false));
        nerveDoctor.seeDoctor(xiaoGong);