观察者模式
Define a one-to-many dependency between objects so that when one object change state,
all its dependents are notified and updated automatically.
定义对象间一种一对多的依赖关系,这样,当一的一方状态改变时,所有它的依赖者都会被自动通知。
public class Observer {
/**
* 观察者模式:
* Define a one-to-many dependency between objects so that when one object change state,
* all its dependents are notified and updated automatically.
* 定义对象间一种一对多的依赖关系,这样,当一的一方状态改变时,所有它的依赖者都会被自动通知。
*/
@Test
public void all() {
final Student student = Student.builder().name("二狗子").build();
final Monitor monitor = Monitor.builder().name("monitor").build();
final Teacher teacher = Teacher.builder().name("teacher").build();
student.addObserver(monitor);
student.addObserver(teacher);
student.play();
}
}
/**
* 1)观察者需要观察的事件或行为
*/
interface IObserver {
void inform(String event);
}
/**
* 2)被观察者对观察者的操作接口
*/
interface IObserverOperate {
void addObserver(IObserver observer);
void removeObserver(IObserver observer);
void notifyAll(String target);
}
/**
* 3)具体的观察者实现
*/
@Builder
@Slf4j
class Monitor implements IObserver {
private final String name;
@Override
public void inform(String event) {
log.info("{} {}", name, event);
}
}
/**
* 4)具体的观察者实现
*/
@Builder
@Slf4j
class Teacher implements IObserver {
private final String name;
@Override
public void inform(String event) {
log.info("{} {}", name, event);
}
}
/**
* 4)具体的被观察者实现,实现了观察者管理接口
*/
@Builder
class Student implements IObserverOperate {
private final String name;
@Default
private final List<IObserver> observers = Lists.newArrayList();
@Override
public void addObserver(IObserver observer) {
observers.add(observer);
}
@Override
public void removeObserver(IObserver observer) {
observers.remove(observer);
}
@Override
public void notifyAll(String target) {
observers.forEach(observer -> observer.inform(target));
}
public void play() {
/**
* 一旦主体状态变化,立即通知所有的观察者
*/
final String event = name + " is plaing";
notifyAll(event);
}
}