import java.util.ArrayList;
import java.util.List;
// 观察者接口
interface Observer {
void update(String message);
}
// 具体观察者
class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
// 被观察者
class Subject {
private List<Observer> observers = new ArrayList<>();
public void register(Observer observer) {
observers.add(observer);
}
public void unregister(Observer observer) {
observers.remove(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Subject subject = new Subject();
// 创建观察者
Observer observer1 = new ConcreteObserver("Observer1");
Observer observer2 = new ConcreteObserver("Observer2");
// 注册观察者
subject.register(observer1);
subject.register(observer2);
// 发送通知
subject.notifyObservers("Hello, Observers!");
}
}
Subject是被观察的对象,Observer是观察者。当Subject的状态发生改变时,它会通知所有注册的Observer