某图书管理系统中管理着两种类型的文献:图书和论文。现在要求统计所有馆藏文献的总页码(假设图书馆中有一本540页的图书和两篇各25页的论文,那么馆藏文献的总页码就是590页)。采用Visitor(访问者)模式实现该要求,得到如图7.16所示的类图。
访问者模式让增加新的操作很容易,因为增加新的操作就意味着增加一个新的访问者。访问者模式将有关的行为集中到一个访问者对象中。
【Java 代码】
import java.util.*;interface Libraryvisitor {void visit(Book p_book); //访问Bookvoid visit(Article p_article);//访问 Articlevoid printSum();
}class LibrarysumPrintvisitor implements Libraryvisitor {//打印总页数private int sum = 0;public void visit(Book p_book) {sum = sum + P_book.getNumberOfPages();public void visit (Article p_article){sum = sum + p_article.getNumberOfPages0;}public void printsum () {System.out.println("SUM=" + sum);}}interface libraryItemInterface {void accept(LibraryVisitor visitor); // 声明了一个接受操作,接受一个访问者对象}class Article implements libraryItemInterface {private String m_title; //论文名private String m_author; //论文作者private intm_start_page;private int m_end_page;public Article(String p_author, string p_title, int p_start_page, intp_end_page) {m title = p title;m_author = p_author;m_end_page = p_end_page;}public int qetNumbelOfPages() {rctum m_end_page -m_start_page;}public void accept(Libraryvisitor visitor) {visitor.visit(this); // 该访问者的具体实现}}class Book implements LibraryItemInterface {private String m_title; //书名private String m_author;//书作者private intm_pages;//页教public Book(String p_author, String p_title, int p_ pages) {m_title = p_title;m_author = p_author;m_pages = p_pages;}public int getNumberOfPages() {return m_pages;}public void accept(LibraryVisitor visitor) {visitor.visit(this);// 该访问者的具体实现}}
}