2011年4月18日 星期一

GoF Behavioral - Chain of Responsibility


  • Intent


to avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request.

the request is passed along the chain of receving objects until an object process it.


  • Benefits


1. 降低了耦合程度

2.添增了物件實體需要被指派負責不同工作內容的彈性..ex : obj.chain(xxx).chain(yyy)

3.it allows a set of classes to act as one; events produced in one class can be sent to other handler within the

composition.


  • 適用情境




  1. More than one object can handle a request, and the handler is unknown

  2. A request is to be issued to one of several objects, and the receiver is not specified explicitly.

  3. The set of objects able to handle the request is to be specified dynamically.




  • 常見API - RequestDispatcher in the jsp/servlet

  • Class Diagram


[caption id="attachment_228" align="alignnone" width="456" caption="CORPattern"]CORPattern[/caption]

[caption id="attachment_232" align="alignnone" width="630" caption="CORPattern-2"]CORPattern-2[/caption]

  • Sample Code



package corpattern;

interface HandlerIF {

public void processRequest(Request req);
}

class ConcreteHandlerA implements HandlerIF {

@Override
public void processRequest(Request req) {
// TODO Auto-generated method stub
switch (req.getType()) {
case Request.EQUITY_ORDER:
handleIt(req);
break;
case Request.BOND_ORDER:
System.out.println("send to the 2nd Handler now ~");
new ConcreteHandlerB().processRequest(req);
break;
}
}

private void handleIt(Request req) {
System.out.println("i'm concreateA , req is solved..");
}

}

class ConcreteHandlerB implements HandlerIF {

@Override
public void processRequest(Request req) {
// TODO Auto-generated method stub
handleIt(req);
}

private void handleIt(Request req) {
System.out.println("i'm concreteB , req is solved by 2nd handler ");
}

}

class Request {

public final static int EQUITY_ORDER = 100;
public final static int BOND_ORDER = 200;
private int type;

public Request(int parm) throws Exception {
if ((parm == EQUITY_ORDER) || (parm == BOND_ORDER)) {
this.type = parm;
} else {
throw new Exception("Unknown request type ! " + parm);
}
}

public int getType() {

return this.type;
}
}

public class Corpattern {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Request equityOrderRequest = new Request(Request.EQUITY_ORDER);
Request bondOrderRequest = new Request(Request.BOND_ORDER);
HandlerIF handler = new ConcreteHandlerA();
handler.processRequest(equityOrderRequest);
handler.processRequest(bondOrderRequest);

} catch (Exception e) {

}
}

}

沒有留言: