JAVA 设计模式 职责链模式
目录
用途
职责链模式是一种行为型模式。
结构
图-职责链模式
Handler : 定义一个处理请求的接口。(可选的)实现设置后继者的方法。
abstract class Handler {
protected Handler successor;
public void SetSuccesssor(Handler successor) {
this.successor = successor;
}
public abstract void HandlerRequest(int request);
}
protected Handler successor;
public void SetSuccesssor(Handler successor) {
this.successor = successor;
}
public abstract void HandlerRequest(int request);
}
ConcreteHandler : 处理它所负责的请求,可以访问它的后继者,如果可处理该请求,就处理之,否则就将请求转发给它的后继者。
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);
}
}
}
@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);
}
}
}
Client : 需要设置一个职责链的各环节对象串联起来。
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);
}
}
}
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);
}
}
}