1,首先设置一个主题类(即被观察者),继承自Observable类,代码如下
@Slf4j
public class SubjectDemo extends Observable {
String message ;
public void setMessage(String s){
this.message = s;
log.info("set message {}",this.message);
setChanged();
notifyObservers(s);
}
}
2,设置A,B,C三个观察者小弟,以A为例,要实现Observer接口
@Slf4j
public class ObserverCustomerA implements Observer {
SubjectDemo subjectDemo;
String msg;
public void update(Observable o, Object arg) {
if (o instanceof SubjectDemo){
log.info("OCA received params {}",(String)arg);
}
}
}
3,设置一个启动类
@Slf4j
public class ObserverModeMain {
public static void main(String[] args) {
SubjectDemo subjectDemo = new SubjectDemo();
subjectDemo.addObserver(new ObserverCustomerA());
subjectDemo.addObserver(new ObserverCustomerB());
subjectDemo.addObserver(new ObserverCustomerC());
subjectDemo.setMessage("hello observer");
}
}
4,查看输出结果
10:57:54.176 [main] INFO m.r.designmode.observer.SubjectDemo - set message hello observer
10:57:54.179 [main] INFO m.r.d.observer.ObserverCustomerC - OCC received params hello observer
10:57:54.179 [main] INFO m.r.d.observer.ObserverCustomerB - OCB received params hello observer
10:57:54.179 [main] INFO m.r.d.observer.ObserverCustomerA - OCA received params hello observer