要實現觀察者模式,你可以按照以下步驟進行:
public interface Observer {
void update();
}
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
public class ConcreteObserver implements Observer {
@Override
public void update() {
// 處理被觀察者的通知
}
}
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
public class Main {
public static void main(String[] args) {
ConcreteObserver observer1 = new ConcreteObserver();
ConcreteObserver observer2 = new ConcreteObserver();
ConcreteSubject subject = new ConcreteSubject();
subject.registerObserver(observer1);
subject.registerObserver(observer2);
// 進行一些操作...
subject.notifyObservers();
}
}
這樣,當被觀察者進行通知時,具體觀察者的 update()
方法將被調用,從而實現了觀察者模式。