1. 程式人生 > >Android 設計模式 觀察者模式

Android 設計模式 觀察者模式

觀察者:

public interface EventObserver<T> {

    void notifyData(T bean);
}

被觀察者:

public class EventObservable<T> {

    private List<EventObserver<T>> list = new ArrayList<>();
    public void register(EventObserver<T> eventObserver) {
        if (list == null || eventObserver == null
) return; synchronized (this) { if (!list.contains(eventObserver)) list.add(eventObserver); } } public void unregister(EventObserver<T> eventObserver) { if (list == null || list.size() == 0 || eventObserver == null) return;
synchronized (this) { if (list.contains(eventObserver)) list.remove(eventObserver); } } public void notifyData(T bean) { if (list == null || list.size() == 0 || bean == null) return; for (EventObserver<T> eventObserver : list
) { eventObserver.notifyData(bean); } } }

測試bean:

public class EventBean {

    private String event;
    public EventBean() {
    }

    public EventBean(String event) {
        this.event = event;
}

    public String getEvent() {
        return event;
}

    public void setEvent(String event) {
        this.event = event;
}

    @Override
public String toString() {
        return "EventBean{" +
                "event='" + event + '\'' +
                '}';
}
}

使用方法:

EventObservable<EventBean> eventObservable = new EventObservable<>();
EventObserver<EventBean> eventObserver = new EventObserver<EventBean>() {
    @Override
public void notifyData(EventBean bean) {
        //do something
}
};
eventObservable.register(eventObserver);
eventObservable.notifyData(new EventBean("event"));