JAVA设计模式-观察者模式(PropertyChangeEven、PropertyChangeListener实现)

因为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]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值