解释
Chain-of-responsibility pattern:该模式包含一些命令对象和一系列的处理对象。每个处理对象决定可以处理哪些命令对象,同时通过在处理链的末尾添加新的处理对象的方式把不能处理的命令对象传递给该链中的下一个处理对象。 —— [ 维基百科 ]
结构
实例代码
代码说明:
请假时间为一天, 导师可以批准,
两天和三天的假,辅导员可以批准,
三天以上的假,需要研究生院批准。
第一步:请假条信息设置
class Information{
private String stname,grade,thing;
private int date;
public Information(String stname,String grade,String thing,int date) {
this.stname=stname;
this.grade=grade;
this.thing=thing;
this.date=date;
}
public String getStname() {
return stname;
}
public void setStname(String stname) {
this.stname = stname;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getThing() {
return thing;
}
public void setThing(String thing) {
this.thing = thing;
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
}
第二步:抽象处理类,生成相应子类
abstract class People{
protected String name;
protected People nextone;
public People(String name){
this.name=name;
}
public void setNextone(People nextone){
this.nextone=nextone;
}
public abstract void process(Information context);
}
class Teacher extends People{
public Teacher(String name) {
super(name);
}
public void process(Information context){
if (context.getDate()==1) {
System.out.println("针对"+context.getGrade()+context.getStname()+",因为"+ context.getThing()+"而请假"+context.getDate()+"天的情况,"+this.name+"准许请假!");
}else {
this.nextone.process(context);
}
}
}
class FuDaoYuan extends People{
public FuDaoYuan(String name) {
super(name);
}
public void process(Information context){
if (context.getDate()<=3) {
System.out.println("针对"+context.getGrade()+context.getStname()+",因为"+ context.getThing()+"而请假"+context.getDate()+"天的情况,"+this.name+"准许请假!");
}else {
this.nextone.process(context);
}
}
}
class Academy extends People{
public Academy(String name) {
super(name);
}
public void process(Information context){
if (context.getDate()>=5) {
System.out.println("针对"+context.getGrade()+context.getStname()+",因为"+ context.getThing()+"而请假"+context.getDate()+"天的情况,"+this.name+"准许请假!");
}else {
this.nextone.process(context);
}
}
}
第三步:客户端测试
class Client{
public static void main(String[] args) {
People teacher,fudaoyuan,academy;
teacher=new Teacher("导师");
fudaoyuan=new FuDaoYuan("辅导员");
academy=new Academy("研究生院");
teacher.setNextone(fudaoyuan);
fudaoyuan.setNextone(academy);
Information a1=new Information("张三", "研三", "外出调研", 1);
teacher.process(a1);
Information a2=new Information("李四", "研一", "心理咨询师考试", 1);
teacher.process(a2);
Information a3=new Information("Jack", "研一", "外出调研", 3);
teacher.process(a3);
Information a4=new Information("May", "研二", "出国参加论坛", 8);
teacher.process(a4);
Information a5=new Information("Tom", "研四", "就医", 2);
teacher.process(a5);
}
}
程序效果:
针对研三张三,因为外出调研而请假1天的情况,导师准许请假!
针对研一李四,因为心理咨询师考试而请假1天的情况,导师准许请假!
针对研一Jack,因为外出调研而请假3天的情况,辅导员准许请假!
针对研二May,因为出国参加论坛而请假8天的情况,研究生院准许请假!
针对研四Tom,因为就医而请假2天的情况,辅导员准许请假!