创建抽象责任类
package com.zhao.sina.design.patterns.chain;
public abstract class Leader
{
private Leader next;
public void setNext(Leader next)
{
this.next=next;
}
public Leader getNext()
{
return next;
}
//处理请求的方法
public abstract void handleRequest(int LeaveDays);
}
一级处理者
package com.zhao.sina.design.patterns.chain;
//具体处理者1:班主任类
public class ClassAdviser extends Leader {
public void handleRequest(int LeaveDays) {
if (LeaveDays <= 3) {
System.out.println("班主任批准您请假" + LeaveDays + "天。");
} else {
if (getNext() != null) {
getNext().handleRequest(LeaveDays);
} else {
System.out.println("请假天数太多,没有人批准该假条!");
}
}
}
}
二级处理者
package com.zhao.sina.design.patterns.chain;
//具体处理者2:系主任类
public class DepartmentHead extends Leader {
public void handleRequest(int LeaveDays) {
if (LeaveDays <= 7) {
System.out.println("系主任批准您请假" + LeaveDays + "天。");
} else {
if (getNext() != null) {
getNext().handleRequest(LeaveDays);
} else {
System.out.println("请假天数太多,没有人批准该假条!");
}
}
}
}
三级处理者
package com.zhao.sina.design.patterns.chain;
//具体处理者3:院长类
public class Dean extends Leader {
public void handleRequest(int LeaveDays) {
if (LeaveDays <= 15) {
System.out.println("院长批准您请假" + LeaveDays + "天。");
} else {
if (getNext() != null) {
getNext().handleRequest(LeaveDays);
} else {
System.out.println("请假天数太多,没有人批准该假条!");
}
}
}
}
责任链测试
package com.zhao.sina.design.patterns.chain;
public class ChainTest {
public static void main(String[] args)
{
//组装责任链
Leader teacher = assemblyChain();
//提交请求
teacher.handleRequest(50);
}
private static Leader assemblyChain() {
Leader classAdviser=new ClassAdviser();
Leader mentHead=new DepartmentHead();
Leader dean=new Dean();
classAdviser.setNext(mentHead);
mentHead.setNext(dean);
return classAdviser;
}
}