当一个对象发生变化时另一个对象也要变化,用观察者来观察对象的变化来通知另一个对象更新
Observable
import java.util.ArrayList;
import java.util.List;
public class Observable<T> {
private final T state;
private final List<Observer> observers = new ArrayList<>();
public Observable(T state) {
this.state = state;
}
public static <T> Observable just(T state) {
return new Observable(state);
}
public Observable add(Observer observer) {
observers.add(observer);
return this;
}
public void change() {
observers.forEach(o -> o.update(state));
}
}
Observer
import java.util.function.Consumer;
public class Observer {
private Consumer consumer;
private String name;
public Observer(Consumer consumer) {
this.consumer = consumer;
}
public <T> void update(T state) {
consumer.accept(state);
}
}
Client
/**
* 观察者模式:要在被观察对象中指定观察者建立对象关联,当被观察对象状态改变时,触发观察者更新事件
*/
public class Client {
public static void main(String[] args) {
Observable.just("hello world")
.add(new Observer(System.out::println))
.add(new Observer(System.out::println))
.change();
}
}