题目:
一个读者可以订阅一种或者几种报纸,根据提供的newscafe文件夹下的代码架构,补充代码功能,并验证结果。示例运行结果如下:
Jill reads: The Times : Stormy weather!
Jill reads: The Guardian : Bad news!
Jack reads: The Guardian : Bad news!
Jill reads: The Guardian : Good news!
Jack reads: The Guardian : Good news!
Jill reads: The Times : Sunny weather!
实现代码:
Reader.java
package Newscafe;
class Reader {
private String name;
Reader(String name) {
this.name = name;
}
//get the read article name based on newspaper Issue number
void readArticle(Newspaper newspaper) {
int i=newspaper.getIssue();
if(newspaper.getArticle(i)!=null)
{
System.out.println(this.name+" reads:"+newspaper.getName()
+":"+newspaper.getArticle(i));
}
}
//subscribe the newspaper
void subscribe(Newspaper newspaper) {
newspaper.register(this);
} }
Newspaper.java
package Newscafe;
import java.util.*;
class Newspaper {
private String name;
private List<String> articles;
private List<Reader> readers;
Newspaper(String name) {
articles = new ArrayList<String>();
readers = new ArrayList<Reader>();
this.name = name;
}
//add the article to the articles list and make an announcement.
void addArticle(String article) {
articles.add(article);
announce();
}
//get the issue number for this article
String getArticle(int issue) {
if(1<=issue||issue<=articles.size())
{
return articles.get(issue-1);
}
System.out.println("期号错误");
return null;
}
//issue number is the number to track the added articles
//hint: the issue number of newly added article is the size of articles
int getIssue() {
return articles.size(); //返回期号
}
String getName()
{
return this.name;
}
//add a new reader to the readers list
void register(Reader reader) {
readers.add(reader);
}
//remove a reader from the readers list
void unregister(Reader reader) {
readers.remove(reader);
}
//let all readers who subscribe this newspaper read this article
void announce() {
for(Reader r:readers)
{
r.readArticle(this);
}
}
}
Newscafe.java
package Newscafe;
class Newscafe {
public static void main(String[] args) {
Reader jill = new Reader("Jill");
Reader jack = new Reader("Jack");
Newspaper times = new Newspaper("The Times");
Newspaper guardian = new Newspaper("The Guardian");
jill.subscribe(times);
times.addArticle("Stormy weather!");
jill.subscribe(guardian);
jack.subscribe(guardian);
guardian.addArticle("Bad news!");
guardian.addArticle("Good news!");
times.addArticle("Sunny weather!");
}
}