觀察者模式
下面是一個簡單的觀察者模式的示例程式碼,使用Java語言實現:
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 + " 收到訊息:" + message);
}
}
// 主題介面
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers(String message);
}
// 具體主題類
class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
// 測試類
public class ObserverPatternExample {
public static void main(String[] args) {
Subject subject = new ConcreteSubject();
Observer observer1 = new ConcreteObserver("Observer 1");
Observer observer2 = new ConcreteObserver("Observer 2");
Observer observer3 = new ConcreteObserver("Observer 3");
// 新增觀察者
subject.attach(observer1);
subject.attach(observer2);
subject.attach(observer3);
// 傳送通知
subject.notifyObservers("Hello, observers!");
// 移除觀察者
subject.detach(observer2);
// 傳送通知
subject.notifyObservers("Hello again!");
}
}