5.某图书管理系统中管理着两种类型的文献:图书和论文。现在要求统计所有馆藏文献的总页码(假设图书馆中有一本540页的图书和两篇各25页的论文,那么馆藏文献的总页码就是590页)。采用Visitor(访问者)模式实现该要求,得到如图6-1所示的类图。
图6-1 Visitor模式类图
【Java代码】
import java.util.*;
interface LibraryVisitor{
(1);
(2);
void 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.getNumberOfPages( );
}
public void printSum( ){
System.out.println("SUM="+sum);
}
}
interface LibraryItemInterface{
(3);
}
class?Article implements LibraryItemInterface{
private String m_title;//论文名
private String m_author;//论文作者
private int?m_start_page;
private int?m_end_page;
public Article(String p_author,String p_title,int p_start_page,int p_end_page){
m_title=p_title;
m_author=p_author;
m_end_page=p_end_page;
}
public int getNumberOfPages( ){
return m_end_page-m_start_page;
}
public void accept(LibraryVisitor Visitor){
(4);
}
}
class Book implements LibraryItemInterface{
private String m_title;//书名
private String m_author;//书作者
private int?m_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){
(5);
}
}