参考文档:
1.设计模式-可复用面向对象软件的基础
2.http://blog.csdn.net/hguisu/article/details/7547231(设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为型))
职责链模式(Chain of Responsibility)(对象行为型)
在这里讲的是书中实现的案例。
先看一下这个责任链模式的结构:
一个典型的对象结构可能如下图所示:
这一模式的想法是,给多个对象处理一个请求的机会,从而解耦发送者和接受者。该请求沿对象链传递直至其中一个对象处理它,如下图所示。
下面的交互框图(diagram) 说明了帮助请求怎样沿链传递:
代码实现:
下面的例子举例说明了在一个像前面描述的在线帮助系统中,职责链是如何处理请求的。
HelpHandler.java:
package com.rick.designpattern.chain_of_responsibility; /** * Created by MyPC on 2017/6/16. */ public class HelpHandler { public static final int NO_HELP_TOPIC = -1; private HelpHandler successor; private int topic; public HelpHandler(HelpHandler helpHandler, int topic) { this.successor = helpHandler; this.topic = topic; } public void setHandler(HelpHandler h, int topic) { this.successor = h; this.topic = topic; } public boolean hasHelp() { return topic != NO_HELP_TOPIC; } public void handleHelp() { if (null != successor) { successor.handleHelp(); } } }
Widget.java:
package com.rick.designpattern.chain_of_responsibility; /** * Created by MyPC on 2017/6/16. */ public class Widget extends HelpHandler { public Widget(Widget parent, int topic) { super(parent, topic); } }
Dialog.java:
package com.rick.designpattern.chain_of_responsibility; /** * Created by MyPC on 2017/6/16. */ public class Dialog extends Widget { public Dialog(HelpHandler helpHandler, int topic) { super(null, topic); setHandler(helpHandler, topic); } @Override public void handleHelp() { if (hasHelp()) { System.out.println("Dialog is handleHelp"); } else { super.handleHelp(); } } }
Button.java:
package com.rick.designpattern.chain_of_responsibility; /** * Created by MyPC on 2017/6/16. */ public class Button extends Dialog { public Button(Dialog parent, int topic) { super(parent, topic); } @Override public void handleHelp() { if (hasHelp()) { System.out.println("Button is handleHelp"); } else { super.handleHelp(); } } }
Application.java:
package com.rick.designpattern.chain_of_responsibility; /** * Created by MyPC on 2017/6/16. */ public class Application extends HelpHandler { public Application(int topic) { super(null, topic); } @Override public void handleHelp() { System.out.println("Application is handleHelp"); } }
Client.java:
package com.rick.designpattern.chain_of_responsibility; import com.rick.designpattern.visitor.PricingVisitor; /** * Created by MyPC on 2017/6/16. */ public class Client { public static final int PRINT_TOPIC = 1, PAPER_ORIENTATION_TOPIC = 2, APPLICATION_TOPIC = 3; public static void main(String[] args) { Application application = new Application(APPLICATION_TOPIC); Dialog dialog = new Dialog(application, PRINT_TOPIC); Button button = new Button(dialog, HelpHandler.NO_HELP_TOPIC); button.handleHelp(); } }