Interceptor的实现

public interface Action { 
public String execute() throws Exception;
}

public class TestAction implements Action {

public String execute() throws Exception {
System.out.println("action exe");
return "success";
}

}

public interface Interceptor {
public String intercept(ActionInvocation invocation) throws Exception;
}

public class Test1Intercpetor implements Interceptor{

public String intercept(ActionInvocation invocation) throws Exception{
System.out.println("hello!in test1");
String code= invocation.invoke();
System.out.println("end!in test1");
return code;
}

}

public class Test2Intercpetor implements Interceptor{

public String intercept(ActionInvocation invocation) throws Exception{
System.out.println("hello!in test2");
String code= invocation.invoke();
System.out.println("end!in test2");
return code;
}

}

public interface ActionInvocation {
public String invoke() throws Exception ;
}


public class DefaultInvocation implements ActionInvocation{

private List<Interceptor> interceptors =new ArrayList<Interceptor>();
private int index=-1;
private String result;
public String invoke() throws Exception {

if(index==interceptors.size()-1){
result=action.execute();
}else
{
index++;
result=((Interceptor)interceptors.get(index)).intercept(this);
System.out.println("????"+result);

}
return result;
}

public void addInterceptor(Interceptor interceptor){
interceptors.add(interceptor);
}

private Action action;
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}


}


public class Test {
public static void main(String[] args){
DefaultInvocation d=new DefaultInvocation();
d.setAction(new TestAction());
d.addInterceptor(new Test1Intercpetor());
d.addInterceptor(new Test2Intercpetor());
try {
d.invoke();
} catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值