What is the best way to implement notification abo

2019-04-13 20:52发布

A have a bean (POJO-like) and want to make model for GUI component of it. So I need to notify about each property change in order GUI component can reflect.

How to do this? Should I put notification and listener storage code just inside my bean? But this will make it "dirty". May be write some wrapper? But this will duplicate getters and setters.

Are there any libraries and/or helper objects for this in Commons or somewhere else?

UPDATE

Also suppose I have AbstractList<E> implementation. How to "propertize" it quickly, i.e. make it to notify listeners about changes? For example, by firing ListDataEvent. I know I can implement AbstractListModel<E> instead of AbstractList<E> but it looks worse. I wish to stay mostly "pojo-like"...

2条回答
Explosion°爆炸
2楼-- · 2019-04-13 21:40

Take a look at FXCollections (JDK 7):

List<String> list = new ArrayList<String>();

list.add("s1");
list.add("s2");

ObservableList<String> observableList = FXCollections.observableList(list);

observableList.addListener(new ListChangeListener<String>() {
    @Override
    public void onChanged(Change<? extends String> change) {
        while (change.next()) {
            if(change.wasAdded()){
                System.out.printf("added: %s, from: %d, to: %d%n", change.getAddedSubList(), change.getFrom(), change.getTo());
            }else
            if(change.wasReplaced()){
                System.out.printf("replaced: %s, from: %d, to: %d%n", change.getAddedSubList(), change.getFrom(), change.getTo());
            }
        }
    }
});

observableList.add("s3");
observableList.set(1, "s1-new-value");

This will result into an output:

added: [s3], from: 2, to: 3
added: [s1-new-value], from: 1, to: 2
查看更多
甜甜的少女心
3楼-- · 2019-04-13 21:41

You can either make use of something like PropertyChangeSuppport or roll your own, for example...

public class Person {

    private String name;
    private final PropertyChangeSupport support;

    public Person() {
        this.support = new PropertyChangeSupport(this);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        support.addPropertyChangeListener(listener);
    }

    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
        support.addPropertyChangeListener(propertyName, listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        support.removePropertyChangeListener(listener);
    }

    public void setName(String value) {
        if (name == null ? value != null : !name.equals(value)) {

            String old = name;
            name = value;
            support.firePropertyChange(name, old, name);

        }
    }

    public String getName() {
        return name;
    }                       
}
查看更多
登录 后发表回答