【责任链模式】模拟Struts责任链工作流及简单AOP实现

详细代码:http://download.csdn.net/detail/tanxiang21/5402599

模拟Struts2的工作责任链过程,接口调用invoke方法执行

public interface ActionInvocation{

    Object getAction();
    boolean isExecuted();
    Result getResult() throws Exception;
    String getResultCode();
    void setResultCode(String resultCode);
    String invoke() throws Exception;
    String invokeActionOnly() throws Exception;
}
接口实现类,这里具体的流程执行内容,由外部传入,不同于Struts2才有容器注入方式
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

public class DefaultActionInvocation implements ActionInvocation {
	protected Iterator<InterceptorMapping> interceptors;
	protected Action action = new SelfAction();

	@SuppressWarnings("rawtypes")
	private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
	private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];

	protected Result result;
	protected String resultCode;

	protected boolean executed = false;

	//这里我们外部传入内容,Struts采用inject注入以及调用init方法初始化内容
	public DefaultActionInvocation(List<InterceptorMapping> interceptorsTree,
			Action action) {
		this.interceptors = interceptorsTree.iterator();
		this.action = action;
	}

	public String invoke() throws Exception {

		if (executed) {
			throw new IllegalStateException("Action has already executed");
		}

		//遍历拦截器
		if (interceptors.hasNext()) {
			final InterceptorMapping interceptor = interceptors.next();
			resultCode = interceptor.getInterceptor().intercept(
					DefaultActionInvocation.this);
		} 
		//执行Action
		else{
			resultCode = invokeActionOnly();
		}
		
		//这里打个假设,在Struts实际会根据resultCode,判断创建哪类Result以及执行chian转发等
		//这里只是一个demo,我们模拟执行的流程		
		if(Action.SUCCESS.equals(resultCode)){  
			executeResult();
		}
		

		executed = true;
		return resultCode;

	}

	public String invokeActionOnly() throws Exception {
		return invokeAction(getAction());
	}

	protected String invokeAction(Object action) throws Exception {
		
		boolean methodCalled = false;
		Object methodResult = null;
		Method method = null;
		try {		
			try{
				String methodName = "execute";//这里我们直接设定反射执行execute方法
				method = getAction().getClass().getMethod(methodName,
					EMPTY_CLASS_ARRAY);
			} catch (NoSuchMethodException e) {
				System.out.println("没有此方法");
				methodCalled = true;
			}
			if (!methodCalled) {
				methodResult = method.invoke(action, EMPTY_OBJECT_ARRAY);
			}			
		}catch (InvocationTargetException e) {
			// We try to return the source exception.
			Throwable t = e.getTargetException();
			if (t instanceof Exception) {
				throw (Exception) t;
			} else {
				throw e;
			}
		}
		//返回值直接返回,这里稍微改写了
		return (String) methodResult;
	}

	private void executeResult() throws Exception {
		result = createResult();
		//假设就只执行成功的结果   注意 这里改写了!!!!
		if (result != null && Action.SUCCESS.equals(resultCode)) {
			result.execute(this);
		}
	}

	public Result createResult() throws Exception {
		return new SelfResult();
	}

	public Object getAction() {
		return action;
	}

	public boolean isExecuted() {
		return executed;
	}

	public Result getResult() throws Exception {
		return result;
	}

	public String getResultCode() {
		return resultCode;
	}

	public void setResultCode(String resultCode) {
		if (isExecuted())
			throw new IllegalStateException("Result has already been executed.");
		this.resultCode = resultCode;
	}
}
测试类
public class ResponsibilityChainTest {

	private List<InterceptorMapping> interceptorsTree;
	private Action action;
	private ActionInvocation actionInvocation;
	
	//初始化拦截器,Action,ActionInvocation,相当于容器工作
	@Before	
	public void setUp(){
		
		interceptorsTree = new ArrayList<InterceptorMapping>();
		Interceptor one = new SelfOneInterceptor();
		Interceptor two = new SelfTwoInterceptor();
		InterceptorMapping oneIntercepror = new InterceptorMapping("one", one);
		InterceptorMapping twoIntercepror = new InterceptorMapping("two", two);
		interceptorsTree.add(oneIntercepror);
		interceptorsTree.add(twoIntercepror);
		
		action = new SelfAction();
		
		actionInvocation = new DefaultActionInvocation(interceptorsTree, action);
	}
	
	@Test
	public void test() throws Exception{
		actionInvocation.invoke();		
		assertEquals(Action.SUCCESS,actionInvocation.getResultCode());
	}
}

测试结果:

intercept SelfOneInterceptor before aop
intercept SelfTwoInterceptor before aop
execute SelfAction
------------------------------------Result is success do nothing or other
intercept SelfTwoInterceptor after aop
------------------------------------Result is success do nothing or other
intercept SelfOneInterceptor after aop
------------------------------------Result is success do nothing or other

拦截器类

public interface Interceptor{
 
    void destroy();

    void init();

    String intercept(ActionInvocation invocation) throws Exception;

}

拦截器抽象实现

public abstract class AbstractInterceptor implements Interceptor {
	
    //在初始化时,执行的钩子,实现类可以不实现,这里我们不做模拟
	public void init() {}    
    public void destroy() {}

    /**
     * 拦截器一定需要覆写的方法
     */
    public abstract String intercept(ActionInvocation invocation) throws Exception;
}
拦截器具体实现类1
public class SelfOneInterceptor extends AbstractInterceptor {
    
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
		String result = null ;  	
    	System.out.println("intercept SelfOneInterceptor before aop");		
		result = invocation.invoke(); 		
		System.out.println("intercept SelfOneInterceptor after aop");
		return result; 
    }  
}

拦截器具体实现类2

public class SelfTwoInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
    	String result = null ;   	
    	System.out.println("intercept SelfTwoInterceptor before aop");
		result = invocation.invoke(); 
		System.out.println("intercept SelfTwoInterceptor after aop");				
		return result; 
    }  
}
主执行类接口
public interface Action {

    public static final String SUCCESS = "success";
    public static final String NONE = "none";
    public static final String ERROR = "error";
    public static final String INPUT = "input";
    public static final String LOGIN = "login";

    public String execute() throws Exception;

}

执行实现类

public class SelfAction implements Action{

	@Override
	public String execute() throws Exception {
		System.out.println("execute SelfAction");
		return SUCCESS;
	}
}
结果处理接口
public interface Result {
  
    public void execute(ActionInvocation invocation) throws Exception;

}

结果处理实现类

public class SelfResult implements Result {
	@Override
	public void execute(ActionInvocation invocation) throws Exception {

		System.out.println("------------------------------------Result is "
				+ invocation.getResultCode() + " do nothing or other");
	}
}
拦截器mapping,对应于xml中的名字
public class InterceptorMapping implements Serializable {

    private static final long serialVersionUID = 130216399397955317L;
    private String name;
    private Interceptor interceptor;

    public InterceptorMapping(String name, Interceptor interceptor) {
        this.name = name;
        this.interceptor = interceptor;
    }

    public String getName() {
        return name;
    }

    public Interceptor getInterceptor() {
        return interceptor;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final InterceptorMapping that = (InterceptorMapping) o;

        if (name != null ? !name.equals(that.name) : that.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result;
        result = (name != null ? name.hashCode() : 0);
        return result;
    }
}

你可能感兴趣的:(struts)