责任链模式定义:避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。
有多个对象可以处理同一个请求,具体哪个对象处理该请求由运行时刻自动确定。此时可以使用责任链模式。
以下代码演示责任链模式简单的实际运用:
定义一个抽象类Worker:
package com.ldl.cn.ChainOfResponsibilityModel;
public abstract class Worker {
private Worker nextWorker;
public Worker getNextWorker() {
return nextWorker;
}
public void setNextWorker(Worker nextWorker) {
this.nextWorker = nextWorker;
}
public abstract void doSomething(String content);
}
分别定义Worker1、Worker2继承Worker:
package com.ldl.cn.ChainOfResponsibilityModel;
public class Worker1 extends Worker{
@Override
public void doSomething(String content) {
if (content.contains("job1")) {
System.out.println("Worker1 handles job1");
}else {
if (getNextWorker() != null) {
getNextWorker().doSomething(content);
}else {
System.out.println("Nobody handles "+content);
}
}
}
}
package com.ldl.cn.ChainOfResponsibilityModel;
public class Worker2 extends Worker{
@Override
public void doSomething(String content) {
if (content.contains("job2")) {
System.out.println("Worker2 handles job2");
}else {
if (getNextWorker() != null) {
getNextWorker().doSomething(content);
}else {
System.out.println("Nobody handles "+content);
}
}
}
}
编写测试类:
package com.ldl.cn.ChainOfResponsibilityModel;
public class TestChainOfResponsibilityPattern {
public static void main(String[] args) {
Worker worker1 = new Worker1();
Worker worker2 = new Worker2();
worker1.setNextWorker(worker2);
worker1.doSomething("job1");
worker1.doSomething("job2");
worker1.doSomething("job3");
}
}
运行结果:
Worker1 handles job1
Worker2 handles job2
Nobody handles job3