UML
定义一个处理请示的接口
public class Handler {
protected Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public void HandleRequest(int request) {
}
}
具体的处理请求的类1
public class ConcreteHandler1 extends Handler {
@Override
public void HandleRequest(int request) {
if (request >= 0 && request < 10) {
System.out.println("ConcreteHandler1 处理了请求" + request);
} else if (successor != null) {
successor.HandleRequest(request);
}
}
}
具体的处理请求的类2
public class ConcreteHandler2 extends Handler {
@Override
public void HandleRequest(int request) {
if (request >= 10 && request < 20) {
System.out.println("ConcreteHandler2 处理了请求" + request);
} else if (successor != null) {
successor.HandleRequest(request);
}
}
}
具体的处理请求的类3
public class ConcreteHandler3 extends Handler {
@Override
public void HandleRequest(int request) {
if (request >= 20 && request < 30) {
System.out.println("ConcreteHandler3 处理了请求" + request);
} else if (successor != null) {
successor.HandleRequest(request);
}
}
}
测试类
public class Main {
public static void main(String[] args) {
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.setSuccessor(h2);
h2.setSuccessor(h3);
int[] requests = {1, 2, 3, 11, 12, 13, 21, 22, 23, 99};
for (int request : requests) {
h1.HandleRequest(request);
}
}
}
运行结果