public class Main {
public static void main(String[] args) {
new ActionInvocation().invoke();
}
}
===========================
import java.util.ArrayList;
import java.util.List;
public class ActionInvocation {
List<Interceptor> interceptors = new ArrayList<Interceptor>();
int index = -1;
Action action = new Action();
public ActionInvocation(){
this.interceptors.add(new FristInterceptor());
this.interceptors.add(new SecondInterceptor());
}
public void invoke(){
index++;
if(index >= this.interceptors.size()){
action.execute();
}else{
this.interceptors.get(index).interceptor(this);
System.out.println(this.getClass().getSimpleName());
}
}
}
==================
public interface Interceptor {
public void interceptor(ActionInvocation invocation);
}
===============================================
public class FristInterceptor implements Interceptor {
@Override
public void interceptor(ActionInvocation invocation) {
// TODO Auto-generated method stub
System.out.println(1);
invocation.invoke();
System.out.println(-1);
}
}
====================================================
public class SecondInterceptor implements Interceptor {
@Override
public void interceptor(ActionInvocation invocation) {
// TODO Auto-generated method stub
System.out.println(2);
invocation.invoke();
System.out.println(-2);
}
}
======================================================
public class Action {
public void execute(){
System.out.println("execute !");
}
}
本文介绍了一个简单的Java程序,演示了如何使用拦截器模式来增强Action类的功能。通过定义多个拦截器,可以在执行核心Action前后添加额外的行为。文章展示了具体的代码实现,包括如何创建拦截器、配置ActionInvocation以及执行流程。
6335

被折叠的 条评论
为什么被折叠?



