攔截器模擬


====================================================================



public class ActionProxy {


public static void main(String[] args) {

new ActionInvocation().invoke();
}
}


====================================================================

import java.util.ArrayList;
import java.util.List;




public class ActionInvocation {

private List<Interceptor> inteceptors = new ArrayList<Interceptor>();
// denote the number of interceptors  having  gone.
int index = -1;
private TestAction ta = new TestAction();

public ActionInvocation(){
this.inteceptors.add(new FirstInterceptor());
this.inteceptors.add(new SecondInterceptor());
}



public void invoke() {


index ++;
if(index >= this.inteceptors.size()) {
ta.execute();
}else{

this.inteceptors.get(index).intercept(this);

}
}

}


====================================================================




public interface Interceptor {


public void intercept(ActionInvocation invocation);
}


======================================================================



public class FirstInterceptor implements Interceptor{


@Override
public void intercept(ActionInvocation invocation) {


System.out.println(1);

invocation.invoke();

System.out.println(-1);
}


}


======================================================================




public class SecondInterceptor implements Interceptor{


@Override
public void intercept(ActionInvocation invocation) {


System.out.println(2);

invocation.invoke();

System.out.println(-2);
}


}


======================================================================



public class TestAction {


public void execute() {
System.out.println("execute");
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章