//抽象处理者
public abstract class Handler {
protected Handler successor = null;
public Handler getSuccessor() {
return successor;
}
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract String handleRequest(double fee);
}
//具体处理者
public class ConcreteHandler1 extends Handler{
@Override
public String handleRequest(double fee) {
System.out.println("1最多处理100块;");
if(fee > 100) {
System.out.println("多于100交给高一级处理");
return this.getSuccessor().handleRequest(fee);
}
return "处理成功";
}
}
public class ConcreteHandler2 extends Handler{
@Override
public String handleRequest(double fee) {
System.out.println("2最多处理200块;");
if(fee > 200) {
System.out.println("多于200交给高一级处理");
return this.getSuccessor().handleRequest(fee);
}
return "处理成功";
}
}
public class ConcreteHandler3 extends Handler{
@Override
public String handleRequest(double fee) {
System.out.println("3可处理任何额度;");
return "处理成功";
}
}
public class Test {
public static void main(String[] args) {
Handler h1 = new ConcreteHandler1();//责任链模式
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.setSuccessor(h2);//方便需求修改,流程改变。
h2.setSuccessor(h3);
System.out.println(h1.handleRequest(250));
}
}
结果:
1最多处理100块;
多于100交给高一级处理
2最多处理200块;
多于200交给高一级处理
3可处理任何额度;
处理成功
此外,还可以用一个类来管理处理处理流程,模拟servlet的过滤器Filter
public abstract class Filter {
abstract void doFilter(FilterChain f);
}
public class Filter1 extends Filter{
@Override
void doFilter(FilterChain f) {
System.out.println("Filter1");
f.doFilter(f);
}
}
public class Filter2 extends Filter{
@Override
void doFilter(FilterChain f) {
System.out.println("Filter2");
f.doFilter(f);
}
}
public class FilterChain extends Filter{
private List<Filter> list = new ArrayList<>();
private int index = 0;
void addFilter(Filter f) {
list.add(f);
}
@Override
void doFilter(FilterChain fc) {
if(index == list.size()) {
return ;
}
Filter f = list.get(index);
index ++;
f.doFilter(fc);
}
}
Filter f1 = new Filter1();
Filter f2 = new Filter2();
FilterChain fc = new FilterChain();
fc.addFilter(f1);
fc.addFilter(f2);
fc.doFilter(fc);