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);
}
}