public interface Handler{ public void handleRequest(Request request); } Request类的定义: public class Request{ private String type; public Request(String type){this.type=type;} public String getType(){return type;} public void execute(){ //request真正具体行为代码 } }
那么Handler实现代码如下:
public class ConcreteHandler implements Handler{ private Handler successor; public ConcreteHandler(Handler successor){ this.successor=successor; } public void handleRequest(Request request){ if (request instanceof HelpRequest){ //这里是处理Help的具体代码 }else if (request instanceof PrintRequst){ request.execute(); }else //传递到下一个 successor.handle(request); } } }
这个解决方案就是CoR,在一个链上,都有相应职责的类,因此叫Chain of Responsibility。
扩展性差,因为在CoR中,一定要有一个统一的接口Handler.局限性就在这里。