讨论/《深入浅出设计模式》 - 观察者模式 Observer/
《深入浅出设计模式》 - 观察者模式 Observer
public interface Observer {
    public void update(String event);
}
public class PoliceObserver implements Observer {
    @Override
    public void update(String arg) {
        System.out.println("警察收到消息,罪犯在" + arg);
    }
}
public class Observable {

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

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

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

    public void notifyObservers(String event) {
        for (Observer observer : observers) {
            observer.update(event);
        }
    }
}
public class CriminalObservable extends Observable {
    public void crime(String event) {
        System.out.println("罪犯正在" + event);
        notifyObservers(event);
    }
}
public class Client {
    public static void main(String[] args) {
        CriminalObservable criminalObservable = new CriminalObservable();
        Observer policeObserver1 = new PoliceObserver();
        Observer policeObserver2 = new PoliceObserver();
        criminalObservable.addObserver(policeObserver1);
        criminalObservable.addObserver(policeObserver2);
        criminalObservable.crime("放狗要人");
    }
}
展开全部 2 讨论