行为型模式 --- 责任链模式
2020-08-24 本文已影响0人
十二找十三
package study.org;
public class Demo {
public static void main(String[] args) {
// 组装责任链
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handler3 = new ConcreteHandler3();
handler2.setNext(handler3);
handler1.setNext(handler2);
// 提交请求
handler1.operation("ConcreteHandler2");
}
}
abstract class Handler {
private Handler next;
public Handler getNext() {
return next;
}
public void setNext(Handler next) {
this.next = next;
}
abstract void operation(String tail);
}
class ConcreteHandler1 extends Handler {
@Override
void operation(String tail) {
if ("ConcreteHandler1".equals(tail)) {
System.out.println("ConcreteHandler1 finish");
} else {
if (null != getNext()) {
System.out.println("ConcreteHandler1 next->");
getNext().operation(tail);
} else {
System.out.println("ConcreteHandler1 nothing! or error");
}
}
}
}
class ConcreteHandler2 extends Handler {
@Override
void operation(String tail) {
if ("ConcreteHandler2".equals(tail)) {
System.out.println("ConcreteHandler2 finish");
} else {
if (null != getNext()) {
System.out.println("ConcreteHandler2 next->");
getNext().operation(tail);
} else {
System.out.println("ConcreteHandler2 nothing! or error");
}
}
}
}
class ConcreteHandler3 extends Handler {
@Override
void operation(String tail) {
if ("ConcreteHandler3".equals(tail)) {
System.out.println("ConcreteHandler3 finish");
} else {
if (null != getNext()) {
System.out.println("ConcreteHandler3 next->");
getNext().operation(tail);
} else {
System.out.println("ConcreteHandler3 nothing! or error");
}
}
}
}