类图:
实现:
Observer.java
package com.observer;
public abstract class Observer {
abstract void update(Object... message);
}
ObserverA.java
package com.observer;
public class ObserverA extends Observer {
@Override
void update(Object... message) {
for(Object o : message) {
System.out.println(o);
}
}
}
Subject.java
package com.observer;
import java.util.ArrayList;
import java.util.List;
public abstract class Subject {
private List<Observer> observers = new ArrayList<Observer>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyAllObservers(Object... message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
SubjectA.java
package com.observer;
public class SubjectA extends Subject{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
notifyAllObservers(message);
}
}
Main.java
package com.observer;
public class Main {
public static void main(String args[]) {
Observer observer = new ObserverA();
SubjectA subject = new SubjectA();
subject.addObserver(observer);
subject.setMessage("Hello World");
// Hello World
}
}