JAVA设计模式之观察者模式

一、简介

当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。

二、实现

1、抽象被观察者(Observable)
public abstract class Observable {

    List<Observer> observers = new ArrayList<>();

    public void add(Observer observer){
        observers.add(observer);
    }

    public void remove(Observer observer){
        observers.remove(observer);
    }

    /**
     * 通知观察者
     */
    public abstract void notified();

}
2、抽象观察者(Observer)
public interface Observer {
    public void update(Object o);
}
3、具体的被观察者(ObservableImpl)
public class ObservableImpl extends Observable{

    @Override
    public void notified() {
        for(Observer observer : observers){
            observer.update("send notify");
        }
    }
}
4、具体的观察者(ObserverImpl)
public class ObserverImpl implements Observer {
    private String name;

    public ObserverImpl(String name) {
        this.name = name;
    }

    @Override
    public void update(Object obj) {
        System.out.println(name + "recevie notify:" + (String) obj);
    }
}
5、测试
    public static void main(String[] args) {
        Observable observable = new ObservableImpl();

        Observer observer1 = new ObserverImpl("user1");
        Observer observer2 = new ObserverImpl("user2");
        Observer observer3 = new ObserverImpl("user3");
        //订阅
        observable.add(observer1);
        observable.add(observer2);
        observable.add(observer3);

        observable.notified();

        System.out.println("===============================");
        //取消订阅
        observable.remove(observer2);
        observable.notified();

    }

三、JDK提供的观察者模式实现

1、具体的被观察者(ObservableImpl )
public class ObservableImpl extends Observable {

    public void setData(){
        //设置标记位,必须设置,否者不会发送通知
        setChanged();
        notifyObservers("123");
    }

}
2、具体的观察者(ObserveImpl)
public class ObserveImpl implements Observer {

    private String name;

    public ObserveImpl(String name) {
        this.name = name;
    }

    @Override
    public void update(Observable o, Object arg) {

        System.out.println(name + "update=========" + arg);
    }
}
3、测试
    public static void main(String[] args) {

        Observer observer1 = new ObserveImpl("user1");
        Observer observer2 = new ObserveImpl("user2");
        Observer observer3 = new ObserveImpl("user3");

        ObservableImpl observable = new ObservableImpl();

        observable.addObserver(observer1);
        observable.addObserver(observer2);
        observable.addObserver(observer3);

        observable.setData();

        System.out.println("=============delete==================");

        observable.deleteObserver(observer1);

        observable.setData();
    }

你可能感兴趣的:(java)