一、类图
二、示例代码 - 对猫叫的反应
- 1/4_Observer
public interface Observer {
void response();
}
- 2/4_ConcreteObserver
Dog
public class Dog implements Observer {
@Override
public void response() {
System.out.println("Dog wang~wang~wang~");
}
}
Mouse
public class Mouse implements Observer {
@Override
public void response() {
System.out.println("Mouse run away...");
}
}
- 3/4_Subject
public abstract class Subject {
protected ArrayList<Observer> observers = new ArrayList<>();
public abstract void attach(Observer observer);
public abstract void detach(Observer observer);
public abstract void cry();
}
- 4/4_ConcreteSubject - Cat
public class Cat extends Subject {
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void cry() {
System.out.println("Cat cry!");
System.out.println("-------------------");
for(Object obj : observers){
((Observer)obj).response();
}
}
}
- Client
public class Client {
public static void main(String[] args) {
Observer dog = new Dog();
Observer mouse = new Mouse();
Subject cat = new Cat();
cat.attach(dog);
cat.attach(mouse);
cat.cry();
}
}
输出
Cat cry!
-------------------
Dog wang~wang~wang~
Mouse run away...