指一个对象,要经过一系列的handler 来处理,例如java 的try catch block 里面去catch 不同的Exception.
Usage in JDK:
java.util.logging.Logger#log()
javax.servlet.Filter #doFilter()
代码:
-
package chainofresponsibility;
-
-
//This class is the request object
-
class Number{
-
private int number;
-
-
public int getNumber(){
-
return number;
-
}
-
-
public Number(int num){
-
this.number = num;
-
}
-
}
-
-
//This is the interface that acts as a chain link
-
interface Chain{
-
public void setNext(Chain nextInChain);
-
public void process(Number request);
-
}
-
-
class PositiveNumberProcessor implements Chain{
-
private Chain nextInChain;
-
-
@Override
-
public void setNext(Chain c){
-
nextInChain = c;
-
}
-
-
@Override
-
public void process(Number request){
-
if(request.getNumber() > 0){
-
System.out.println("PositiveNumberProcessor :"+request.getNumber());
-
}else{
-
nextInChain.process(request);
-
}
-
}
-
}
-
-
-
class NegativeNumberProcessor implements Chain{
-
-
private Chain nextInChain;
-
-
@Override
-
public void setNext(Chain c){
-
nextInChain = c;
-
}
-
-
@Override
-
public void process(Number request){
-
if(request.getNumber() < 0){
-
System.out.println("NegativeNumberProcessor :"+request.getNumber());
-
}else{
-
nextInChain.process(request);
-
}
-
}
-
}
-
-
class ZeroProcessor implements Chain{
-
-
private Chain nextInChain;
-
-
@Override
-
public void setNext(Chain c){
-
nextInChain = c;
-
}
-
-
@Override
-
public void process(Number request){
-
if(request.getNumber() == 0){
-
System.out.println("ZeroProcessor :"+request.getNumber());
-
}else{
-
nextInChain.process(request);
-
}
-
}
-
}
-
-
public class ChainOfResponsibilityDemo {
-
public static void main(String[] args){
-
-
//configure Chain of reponsibility
-
Chain c1 = new NegativeNumberProcessor();
-
Chain c2 = new ZeroProcessor();
-
Chain c3 = new PositiveNumberProcessor();
-
c1.setNext(c2);
-
c2.setNext(c3);
-
-
//Calling chain of responsibility
-
c1.process(new Number(99));
-
c1.process(new Number(-30));
-
c1.process(new Number(0));
-
c1.process(new Number(100));
-
}
-
}
阅读(569) | 评论(0) | 转发(0) |