/** * The type of this request, used by each item in the chain to see if they should or can handle * this particular request. */ privatefinal RequestType requestType;
/** * The name of the request. */ privatefinal String name;
/** * Indicates if the request is handled or not. A request can only switch state from unhandled to * handled, there's no way to 'unhandle' a request. */ privateboolean handled;
privatevoidbuildRequestChain(){ handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); for (int i = 0; i < handlers.size() - 1; i++) { handlers.get(i).setNextHandler(handlers.get(i +1)); } }
/** * Handle request by the chain. */ publicvoidmakeRequest(Request req){ handlers.get(0).handle(req); }
}
测试:
1 2 3 4 5 6 7 8
publicstaticvoidmain(String[] args){
Request request = new Request(RequestType.DEFEND_CASTLE, "defend castle"); OrcKing orcKing = new OrcKing(); orcKing.makeRequest(request);
System.out.println(request.isHandled()); }
程序输出:
1 2 3 4
Orc commander handle the request defend castle Orc Officer handle the request defend castle Orc Soldier handle the request defend castle true