设计模式学习之职责链模式
1.名词解释:
职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者自己的耦合关系。将这个对象连成一条链,并沿着这条链传递该对象,直到有一个对象处理它为止。
?
2.代码示例:
?
处理抽象类
package DesignPattern.DutyChain;
import java.util.HashMap;
public abstract class Handler {
???
?protected Handler successor;
?
?public void setSuccessor(Handler handler) {
??this.successor = handler;
?}
?
?abstract void handlerRequest(int request);
}
具体处理类一
package DesignPattern.DutyChain;
import java.util.HashMap;
public class ConcreateHandlerFirst extends Handler{
?@Override
?void handlerRequest(int request) {
??// TODO Auto-generated method stub
??if(request >= 0 && request <=100) {
???//执行具体方法
???System.out.println("Do the request First!");
??} else if(successor != null){
???successor.handlerRequest(request);
??}
??
?}
?
?
}
?
具体处理类二
package DesignPattern.DutyChain;
public class ConcreateHandlerSecond extends Handler{
?@Override
?void handlerRequest(int request) {
??// TODO Auto-generated method stub
??if(request > 100) {
???//执行具体方法
???System.out.println("Do the ConcreateHandlerSecond");
??} else if(successor != null) {
???successor.handlerRequest(request);
??}
?}
}
客户端
package DesignPattern.DutyChain;
public class Client {
?public static void main(String[] args) {
??Handler h1 = new ConcreateHandlerFirst();
??Handler h2 = new ConcreateHandlerSecond();
??h1.setSuccessor(h2);
??int[] requests = {1, 200, 100, 400};
??for(int i = 0; i < requests.length; i++) {
???h1.handlerRequest(requests[i]);
??}
?}
}