abstract class Handler {
protected Handler successor;
public void SetSuccesssor(Handler successor) {
this.successor = successor;
}
public abstract void HandlerRequest(
int request);
}
class ConcreteHandler1
extends Handler {
@Override
public void HandlerRequest(
int request) {
if (request >= 0 && request < 10) {
System.out.println("ConcreteHandler1 处理请求 " + request);
}
else if (
null != successor) {
successor.HandlerRequest(request);
}
}
}
class ConcreteHandler2
extends Handler {
@Override
public void HandlerRequest(
int request) {
if (request >= 10 && request < 20) {
System.out.println("ConcreteHandler2 处理请求 " + request);
}
else if (
null != successor) {
successor.HandlerRequest(request);
}
}
}
class ConcreteHandler3
extends Handler {
@Override
public void HandlerRequest(
int request) {
if (request >= 20 && request < 30) {
System.out.println("ConcreteHandler3 处理请求 " + request);
}
else if (
null != successor) {
successor.HandlerRequest(request);
}
}
}
public class ChainOfResponsibilityPattern {
public static void main(String[] args) {
Handler h1 =
new ConcreteHandler1();
Handler h2 =
new ConcreteHandler2();
Handler h3 =
new ConcreteHandler3();
h1.SetSuccesssor(h2);
h2.SetSuccesssor(h3);
int[] requests = {2, 29, 9, 15, 4, 19};
for (
int i : requests) {
h1.HandlerRequest(i);
}
}
}