其他
Java中的责任链设计模式,太牛了!
public interface Task {
public void run();
}
public class Task1 implements Task{
private Task task;
public Task1() {}
public Task1(Task task){
this.task = task;
}
public void run() {
System.out.println("task1 is run");
if(task != null){
task.run();
}
}
}
public class Task2 implements Task{
private Task task;
public Task2() {}
public Task2(Task task){
this.task = task;
}
public void run() {
System.out.println("task2 is run");
if(task != null){
task.run();
}
}
}
public class Task3 implements Task{
private Task task;
public Task3() {}
public Task3(Task task){
this.task = task;
}
public void run() {
System.out.println("task3 is run");
if(task != null){
task.run();
}
}
}
public class LiabilityChain {
public void runChain(){
Task task3 = new Task1();
Task task2 = new Task2(task3);
Task task1 = new Task3(task2);
task1.run();
}
}
public class ChainTest {
public static void main(String[] args) {
LiabilityChain chain = new LiabilityChain();
chain.runChain();
}
}
以上是一个责任链的简单的实现,如果想要深入理解其思想,建议去观察一个过滤器链的执行源码。
作者:Mazin
https://my.oschina.net/u/3441184/blog/889552
点击「阅读原文」和栈长学更多~