1.观察者 Observer 例如客户
2.被观察者 Observable 例如 商品
3.被观察者基础Observable
public class House extends Observable { private int price; public int getPrice() { return price; } public House(int price){ this.price = price; } public void setPrice(int price) { if (price!=this.price){ this.price = price; setChanged(); //传入的price 会再update方法里收到 即arg notifyObservers(price); } } }
4.观察者实现Observer
public class People implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof House){ System.out.println("房价为"+arg); } } }
5.测试类
public static void main(String[] args) { House house = new House(100); People A = new People(); People B = new People(); People C = new People(); //添加观察者 house.addObserver(A); house.addObserver(B); house.addObserver(C); //取消观察者 house.deleteObserver(A); house.setPrice(1001); }