/**
* 责任链
*/
public class Main {
public static void main(String[] args) {
Request request = new Request("hello");
RequestHandleA requestHandleA = new RequestHandleA();
RequestHandleB requestHandleB = new RequestHandleB();
RequestHandleC requestHandleC = new RequestHandleC();
requestHandleA.setRequestHandle(requestHandleB);
requestHandleB.setRequestHandle(requestHandleC);
requestHandleA.handleRequest(request);
}
}
public interface RequestHandle {
void handleRequest(Request request);
}
public class Request {
private String msg;
public Request(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
public class RequestHandleA implements RequestHandle{
private RequestHandle requestHandle;
public RequestHandle getRequestHandle() {
return requestHandle;
}
public void setRequestHandle(RequestHandle requestHandle) {
this.requestHandle = requestHandle;
}
@Override
public void handleRequest(Request request) {
System.out.println("RequestHandleA 处理了" + request.getMsg());
if (this.requestHandle != null) {
this.requestHandle.handleRequest(request);
}
}
}
public class RequestHandleB implements RequestHandle{
private RequestHandle requestHandle;
public RequestHandle getRequestHandle() {
return requestHandle;
}
public void setRequestHandle(RequestHandle requestHandle) {
this.requestHandle = requestHandle;
}
@Override
public void handleRequest(Request request) {
System.out.println("RequestHandleB 处理了" + request.getMsg());
if (this.requestHandle != null) {
this.requestHandle.handleRequest(request);
}
}
}
public class RequestHandleC implements RequestHandle {
private RequestHandle requestHandle;
public RequestHandle getRequestHandle() {
return requestHandle;
}
public void setRequestHandle(RequestHandle requestHandle) {
this.requestHandle = requestHandle;
}
@Override
public void handleRequest(Request request) {
System.out.println("RequestHandleC 处理了" + request.getMsg());
if (this.requestHandle != null) {
this.requestHandle.handleRequest(request);
}
}
}
用法
举例子,web编程中的过滤器,这就是一个命令,过滤器可以多个,也可以增加减少,但是都实现了同一个接口,所以用起来耦合度是很低,多一个过滤器,配置一下新增一个就好,不用删除一个就行了。
还有常用的flume这个日志工具,里面的组件也是一个套着下一个,这都是很典型的命令设计模式,在软件设计上体现的比较广泛。