??????假设猫是老鼠和狗的观察目标,老鼠和狗是观察者,猫叫老鼠跑,狗也跟着叫,使用观察者模式描述该过程。 问题分析: 下面是观察者模式的模板
import java.util.*;
public abstract class Subject {
protected ArrayList observers<Observer> = new ArrayList();
public void attach(Observer observer) {
observers.add(observer);
}
public void detach(Observer observer) {
observers.remove(observer);
}
public abstract void notify();
}
public class ConcreteSubject extends Subject {
public void notify() {
for(Object obs:observers) {
((Observer)obs).update();
}
}
}
源码: MySubject.java
package observer;
import java.util.*;
public abstract class MySubject {
protected ArrayList observers = new ArrayList();
public void attach(MyObserver observer) {
observers.add(observer);
}
public void detach(MyObserver observer) {
observers.remove(observer);
}
public abstract void cry();
}
MyObserver.java
package observer;
public interface MyObserver {
void response();
}
Cat.java
package observer;
public class Cat extends MySubject{
public void cry() {
System.out.println("猫叫");
System.out.println("-------------------------");
for(Object obs:observers) {
((MyObserver)obs).response();
}
}
}
Dog.java
package observer;
public class Dog implements MyObserver{
public void response() {
System.out.println("狗跟着叫!");
}
}
Mouse.java
package observer;
public class Mouse implements MyObserver{
public void response() {
System.out.println("老鼠努力逃跑!");
}
}
Client.java
package observer;
public class Client {
public static void main(String[] args) {
MySubject subject=new Cat();
MyObserver obs1,obs2,obs3;
obs1=new Mouse();
obs2=new Mouse();
obs3=new Dog();
subject.attach(obs1);
subject.attach(obs2);
subject.attach(obs3);
subject.cry();
}
}
运行结果: https://github.com/MeetNiceMe/java-strategy
|