设计模式之职责链模式

定义:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

结构图:

设计模式之职责链模式_第1张图片

示例代码:

public abstract class Handler {

	protected Handler successor;
	
	public void setSuccessor(Handler successor) {
		this.successor = successor;
	}
	
	public abstract void  handlerRequest(int reqeust);
}
public class ConcreteHandler1 extends Handler {

	@Override
	public void handlerRequest(int request) {
		// TODO Auto-generated method stub
		if (0 <= request && request <= 10) {
			System.out.println(this.getClass().getName() + "  " + request);
		} else {
			successor.handlerRequest(request);
		}
	}

}
public class ConcreteHandler2 extends Handler {

	@Override
	public void handlerRequest(int request) {
		// TODO Auto-generated method stub
		if (10 < request && request <= 20) {
			System.out.println(this.getClass().getName() + "  " + request);
		} else {
			successor.handlerRequest(request);
		}
	}

}
public class ConcreteHandler3 extends Handler {

	@Override
	public void handlerRequest(int request) {
		// TODO Auto-generated method stub
		if (20 < request && request <= 30) {
			System.out.println(this.getClass().getName() + "  " + request);
		} else {
			successor.handlerRequest(request);
		}
	}

}
客户端代码:

public class Client {

	public static void main(String[] args) {
		
		Handler h1 = new ConcreteHandler1();
		Handler h2 = new ConcreteHandler2();
		Handler h3 = new ConcreteHandler3();
		h1.setSuccessor(h2);
		h2.setSuccessor(h3);
		int[] requests = {2, 5, 14, 22, 18, 3, 27, 20 };
		for (int i : requests) {
			h1.handlerRequest(i);
		}
	}
	
}
运行结果如下:

observe.responsibility.ConcreteHandler1  2

observe.responsibility.ConcreteHandler1  5

observe.responsibility.ConcreteHandler2  14

observe.responsibility.ConcreteHandler3  22

observe.responsibility.ConcreteHandler2  18

observe.responsibility.ConcreteHandler1  3

observe.responsibility.ConcreteHandler3  27

observe.responsibility.ConcreteHandler2  20




你可能感兴趣的:(设计模式之职责链模式)