PropertyChangeSupport类--观察者模式

一、概述

  本文主要分享观察者模式在PropertyChangeSupport类的使用,最后给出一个小demo

二、观察者模式简述

  主题:维护观察者列表,当自身状态发生变化时,执行Notify操作(此处一般是在方法内部delegate调用观察者的Update方法)

  

三、PropertyChangeSupport类中观察者模式的使用

    0、构造函数定义被监听对象    

                 pcs = new PropertyChangeSupport(new Person());//在这里主题的状态即为person对象的属性的值的状态,如该对象调用了setAge()方法,那么即为主题的状
          //态发生了变化,应该调用fire方法通知到相应的Listeners

 

    1、map属性用于维护监听者(观察者)列表,其内部实现是 HashMap<String, PropertyChangeListener[]>    

    2、调用addPropertyChangeListener方法为相应属性添加监听器(观察者)

    3、调用firePropertyChange方法类似于Notify方法(当被监听对象属性值发生变化时调用)

    4、在firePropertyChange方法中delegate到每个观察者(PropertyChangeListener)的propertyChange方法。

 

四、小demo

public class TestPropertyChangeSupport {
    public static void main(String[] args) {

        TestPropertyChangeSupport bean = new TestPropertyChangeSupport();//生成一个对象
        PropertyChangeSupport pcs = new PropertyChangeSupport(bean);//定义主题

        pcs.addPropertyChangeListener((evt)-> System.out.println("args = [" + evt + "]"));//添加监听器(观察者)此处不指定属性即为监听所有属性
        //当主题的状态发生变化时,通知到观察者,进行相应的操作
        bean.setExampleProperty("Test");//主题状态发生变化
        pcs.firePropertyChange("exampleProperty",null,"Test");//通知到观察者
    }
    String exampleProperty;

    public String getExampleProperty() {
        return exampleProperty;
    }

    public void setExampleProperty(String exampleProperty) {
        this.exampleProperty = exampleProperty;
    }
}

2018-10-22 00:35:05 

posted @ 2018-10-22 00:37  g今非昔比  阅读(455)  评论(0编辑  收藏  举报