因为Observable类在jdk1.9后已被标记为弃用状态,推荐使用PropertyEvent等方式替代。
所以以下代码是PropertyChangeEven、PropertyChangeListener 实现的观察者模式。
1,创建一个很简单的主类
public class PropertyMain {
public static void main(String[] args) {
PropertyProvider propertyPublishService = new PropertyProvider();
propertyPublishService.publishPropertyChange();
}
}
2,创建生产者
@Singleton
@Slf4j
public class PropertyProvider {
public void publishPropertyChange() {
PropertyChangeSupport support = new PropertyChangeSupport(this);
PropertyListenerCustomerA plca = new PropertyListenerCustomerA();
PropertyListenerCustomerB plcb = new PropertyListenerCustomerB();
PropertyListenerCustomerC plcc = new PropertyListenerCustomerC();
support.addPropertyChangeListener(plca);
support.addPropertyChangeListener(plcb);
support.addPropertyChangeListener(plcc);
support.firePropertyChange("aspirin",18,25);
}
}
3,创建消费者A,B,C,代码以A为例
@Slf4j
public class PropertyListenerCustomerA implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
log.info("PLCA received {}",evt.toString());
}
}
4,查看结果
13:58:17.629 [main] INFO m.r.d.o.p.PropertyListenerCustomerA - PLCA received java.beans.PropertyChangeEvent[propertyName=aspirin; oldValue=18; newValue=25; propagationId=null; source=XXX]
13:58:17.633 [main] INFO m.r.d.o.p.PropertyListenerCustomerB - PLCB received java.beans.PropertyChangeEvent[propertyName=aspirin; oldValue=18; newValue=25; propagationId=null; source=XXX]
13:58:17.633 [main] INFO m.r.d.o.p.PropertyListenerCustomerC - PLCC received java.beans.PropertyChangeEvent[propertyName=aspirin; oldValue=18; newValue=25; propagationId=null; source=XXX]