职责链的模式
一、作用
多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系,将对象连成一条链,并沿着这条链传递该请求,直到有一个对象可以处理它
二、类图
三、实现
(1)定义Handle
public abstract class Handle { protected Handle successor; public void setSeccessor(Handle successor) { this.successor = successor; } public abstract void handleRequest(int request); } public class ConcreteHandleOne extends Handle { @Override public void handleRequest(int request) { if(request >= 0 && request < 10) { System.out.println("One 处理请求"+request); } else if(successor != null) { successor.handleRequest(request); } } } public class ConcreteHandleTwo extends Handle { @Override public void handleRequest(int request) { if(request >= 10 && request < 20) { System.out.println("Two 处理请求"+request); } else if(successor != null) { successor.handleRequest(request); } } } public class ConcreteHandleThree extends Handle { @Override public void handleRequest(int request) { if(request > 20) { System.out.println("Three 处理请求"+request); } else if(successor != null) { successor.handleRequest(request); } } }
(2)Client测试类
public class Client { public static void main(String[] args) { Handle h1 = new ConcreteHandleOne(); Handle h2 = new ConcreteHandleTwo(); Handle h3 = new ConcreteHandleThree(); h1.successor = h2; h2.successor = h3; int request = 14; h1.handleRequest(request); } }
时间: 2024-10-10 09:23:05