程序设计:
猫大叫一声,所有的老鼠都开始逃跑,主人被惊醒。
要求:
(1) 要有联动性,老鼠和主人的行为是被动的;
(2) 考虑可扩展性,猫的叫声可能引起其他联动效应。
参考解答
本题可使用观察者模式,参考类图如下所示:
import java.util.*;
interface Subject //抽象主题
{
public void addObserver(Observer obs);
public void cry();
}
interface Observer //抽象观察者
{
public void response();
}
class Cat implements Subject //具体主题
{
private ArrayList<Observer> list;
public Cat() {
list = new ArrayList<Observer>();
}
public void addObserver(Observer obs) {
list.add(obs);
}
public void cry() {
System.out.println("猫大叫一声!");
for (Object obj : list) {
((Observer) obj).response();
}
}
}
class Mouse implements Observer //具体观察者
{
private String name;
public Mouse(String name, Subject subject) {
this.name = name;
subject.addObserver(this);
}
public void response() {
System.out.println(this.name + "拼命逃跑!");
}
}
class Master implements Observer //具体观察者
{
private String name;
public Master(String name, Subject subject) {
this.name = name;
subject.addObserver(this);
}
public void response() {
System.out.println(this.name + "从美梦中惊醒!");
}
}
class Client //客户端测试类
{
public static void main(String args[])
{
Subject cat = new Cat();
Observer mouse1, mouse2, master;
mouse1 = new Mouse("大老鼠", cat);
mouse2 = new Mouse("小老鼠", cat);
master = new Master("小龙女", cat);
cat.cry();
}
}