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:
Post a Comment