概念:
责任链模式:Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receivering objects and pass the request along the chain until an object handles it.使用多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,知道有对象处理它为止。
实现:
年级抽象类
public abstract class Grade { private Grade grade; private String gradeName; private Integer score; public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public void upgrade() { System.out.println("上" + this.getGradeName()); if (score < 60) { System.out.println("考试没通过,留级"); } else { if (grade == null) { System.out.println("考试通过,毕业"); } else { System.out.println("考试通过,升级"); grade.upgrade(); } } } }
具体年级实现
public class FirstGrade extends Grade { } public class SecondGrade extends Grade { } ...
测试及结果:
@Test public void responsibilityChainTest(){ Grade firstGrade = new FirstGrade(); Grade secondGrade = new SecondGrade(); firstGrade.setGrade(secondGrade); firstGrade.setGradeName("一年级"); firstGrade.setScore(70); secondGrade.setScore(50); secondGrade.setGradeName("二年级"); secondGrade.setGrade(null); firstGrade.upgrade(); }
上一年级
考试通过,升级
上二年级
考试没通过,留级
分析:
1.有点类似递归的方式,所以效率上会有所损失。
2.灵活性较高,可以比较方便的改变运行流程
3.最常见的就是Struts2 请求中的拦截器链,就采用了这种设计模式