Saturday, October 28, 2006

IoC pattern

IoC (Inversion of Control) pattern is a very popular pattern in Java world. It is used in J2EE, Spring, WebWork,... Maybe you don't figure out what is meaning of inversion of control, but actually it's very simple.

To explain inversion of control, we see active and passive actions. In active actions, I say "I'm going to get object X". And in passive actions, I say "Give me object X when I need it". Please see this example, here I implement an action in WebWork, it needs to retrieve a request object to set an attribute.

Active way

public class SetBlahAction implements Action {

public String execute() {
HttpServletRequest request =
ServletActionContext.getHttpServletRequest();
request.setAttribute("blah", "blah");

return SUCCESS;
}

}

Passive way (applied IoC pattern)

public class SetBlahAction implements Action, ServletRequestAware {

private ServletRequest request;

public void setServletRequest(ServletRequest request) {
this.request = request;
}

public String execute() {
request.setAttribute("blah", "blah");

return SUCCESS;
}

}

Here ServletRequestAware interface only defines setServletRequest(ServletRequest).

When using IoC pattern, you can reduce the works you need to do in a class by moving some implementation outside. Also it makes your class more clearly.

No comments: