職責(zé)鏈模式調(diào)用
public class chainHandlerDemo {
public static void main(String[] args) {
PipleLineDemo pipleLineDemo = new PipleLineDemo();
pipleLineDemo.addLast(new Handler1());
pipleLineDemo.addLast(new Handler2());
pipleLineDemo.processStart("I am Head");
}
}
interface AbstractHandler {
void handler(ChainHandlerContext chainHandlerContext, Object args);
}
class Handler1 implements AbstractHandler {
@Override
public void handler(ChainHandlerContext chainHandlerContext, Object args) {
String args2 = args + "--->I am Handler1";
System.out.println(args2);
chainHandlerContext.doNext(args2);
}
}
class PipleLineDemo {
static ChainHandlerContext context = new ChainHandlerContext();
void addLast(AbstractHandler handler) {
while (context.next != null) {
context = context.next;
}
context.next = new ChainHandlerContext();
context.next.handler = handler;
}
public PipleLineDemo() {
context.handler = new AbstractHandler() {
@Override
public void handler(ChainHandlerContext chainHandlerContext, Object args) {
System.out.println(args);
}
};
}
/**
* 啟動(dòng)任務(wù)入口
*/
void processStart(Object args) {
context.doHandler(args);
}
}
class Handler2 implements AbstractHandler {
@Override
public void handler(ChainHandlerContext chainHandlerContext, Object args) {
String args2 = args + "--->I am Handler2";
System.out.println(args2);
chainHandlerContext.doNext(args2);
}
}
class ChainHandlerContext {
ChainHandlerContext next;
AbstractHandler handler;
void doHandler(Object args) {
handler.handler(this, args);
}
void doNext(Object args) {
if (next != null) {
next.doHandler(args);
}
else{
System.out.println(args+"--->I am tail, no any other handler");
}
}
}
測(cè)試結(jié)果