概念:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,知道有一个特对象处理他位置。
java代码:
public class HandlerTest {
public static void main(String[] args) {
ConcreteHandler concreteHandler = new ConcreteHandler();
ConcreteHandler2 concreteHandler2 = new ConcreteHandler2();
concreteHandler.setSuccessor(concreteHandler2);
concreteHandler.HandleRequest(100);
}
}
//处理器抽象类
public abstract class Handler {
public Handler successor;
public void setSuccessor(Handler handler){
successor = handler;
}
public abstract void HandleRequest(int request);
}
//处理器1
public class ConcreteHandler extends Handler {
@Override
public void HandleRequest(int request) {
if (request < 5){
System.out.println("处理器1处理");
}
if (successor != null){
successor.HandleRequest(request);
}
}
}
//处理器2
public class ConcreteHandler2 extends Handler {
@Override
public void HandleRequest(int request) {
if (request > 5){
System.out.println("处理器2处理");
}
if (successor != null){
successor.HandleRequest(request);
}
}