职责链模式设计在线文档帮助系统
任务三:使用职责链模式设计在线文档帮助系统
某公司欲开发一个软件系统的在线文档帮助系统,用户可以在任何一个查询环境中输入查询关键字,如果当前查询环境下没有相关内容,则系统会将查询按照一定的顺序转发给其他查询环境。基于上述需求,采用职责链模式对该系统进行设计。
cclass
7
1
public abstract class SearchContext {protected SearchContext successor;public void setSuccessor(SearchContext successor){this.successor = successor;}public abstract void search(String keyword);
}
2
public class JavaSearchContext extends SearchContext {@Overridepublic void search(String keyword) {//模拟实现if(keyword.contains("Java")){System.out.println("查询关键字Java!");}else{try{successor.search(keyword);}catch(NullPointerException e){System.out.println("未匹配到查询字段!");}}}
}
3
class SQLSearchContext extends SearchContext{@Overridepublic void search(String keyword) {//模拟实现if(keyword.contains("SQL")){System.out.println("查询关键字SQL!");}else{try{successor.search(keyword);}catch(NullPointerException e){System.out.println("未匹配到查询字段!");}}}
}
4
class UMLSearchContext extends SearchContext{@Overridepublic void search(String keyword) {//模拟实现if(keyword.contains("UML")){System.out.println("查询关键字UML!!!");}else{try{successor.search(keyword);}catch(NullPointerException e){System.out.println("未匹配到查询字段!");}}}
}
5
public class Mian {public static void main(String[] args) {String keyword = "UML类图绘制疑惑";SearchContext jContext, sContext, uContext;jContext = new JavaSearchContext();sContext = new SQLSearchContext();uContext = new UMLSearchContext();jContext.setSuccessor(sContext);sContext.setSuccessor(uContext);jContext.search(keyword);keyword = "SQL语句疑惑";jContext.search(keyword);keyword = "Java语法疑惑";jContext.search(keyword);keyword = "各种疑惑";jContext.search(keyword);}}