您的位置:首页 > 其它

行为模式之职责链模式(在线文档帮助系统)

2015-11-26 00:02 477 查看
题目:某公司欲开发一个软件系统的在线文档帮助系统,用户可以在任何一个查询环境中输入查询关键字,如果当前查询环境下没有相关内容,则系统会将查询按照一定的顺序转发给其他查询环境。设查询环境如下:JavaSearchContext、SQLSearchContext、UMLSearchContext。

类图



package 职责链模式实例之在线文档帮助系统;

public class Client {
public static void main(String[] args) {
SearchContext objJava,objSQL,objUML;

objJava = new JavaSearchContext();
objSQL = new SQLSearchContext();
objUML = new UMLSearchContext();

objJava.setSuccessor(objSQL);
objSQL.setSuccessor(objUML);

SearchKey key1 = new SearchKey("java");
objJava.handleRequest(key1);

SearchKey key2 = new SearchKey("sql");
objSQL.handleRequest(key2);

SearchKey key3 = new SearchKey("uml");
objUML.handleRequest(key3);
}
}


package 职责链模式实例之在线文档帮助系统;

public abstract class SearchContext {
protected SearchContext successor;
public void setSuccessor(SearchContext successor) {
this.successor = successor;
}
public abstract void handleRequest(SearchKey key);
}


package 职责链模式实例之在线文档帮助系统;

public class JavaSearchContext extends SearchContext{
public void handleRequest(SearchKey key) {
String key1 = "java";
if(key1.equals(key.getKey()))
System.out.println("在JavaSearchContext中找到了");
else
if(this.successor != null) this.successor.handleRequest(key);
}
}


package 职责链模式实例之在线文档帮助系统;

public class SQLSearchContext extends SearchContext{
public void handleRequest(SearchKey key) {
String key1 = "sql";
if(key1.equals(key.getKey()))
System.out.println("在SQLSearchContext中找到了");
else
if(this.successor != null) this.successor.handleRequest(key);
}
}


package 职责链模式实例之在线文档帮助系统;

public class UMLSearchContext extends SearchContext{
public void handleRequest(SearchKey key) {
String key1 = "uml";
if(key1.equals(key.getKey()))
System.out.println("在UMLSearchContext中找到了");
else
if(this.successor != null) this.successor.handleRequest(key);
}
}


Eclipse运行效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: