要实现观察者模式,你可以按照以下步骤进行:
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()
方法将被调用,从而实现了观察者模式。