package object; import java.util.Observable; import java.util.Observer; /** * @author dayu * @date 2019/03/04 * @Describe 观察者模式 */ public class ObserverDemo { public static void main(String[] args) { Human humanA = new Human(); Human humanB = new Human(); Human humanC = new Human(); Hourse hourse = new Hourse(80000.00); hourse.addObserver(humanA);//必须手动设置观察者 hourse.addObserver(humanB);//设置观察者 hourse.addObserver(humanC);//设置观察者 hourse.setPrice(1000.0);//设置降价,观察者无反应 // hourse.setPrice(1000000.0);//涨价,观察者,有反应 } } // 所有的观察者必须实现Observer class Human implements Observer { // 如果观察的事一旦发生变化,通知 @Override public void update(Observable o, Object arg) { if (o instanceof Hourse) { if (arg instanceof Double) { System.out.println("房价上涨了" + arg); } } } } //被观察者必须继承Observable class Hourse extends Observable { private double price; public Hourse(double price) { this.price = price; } public double getPrice() { return price; } public void setPrice(double price) { if (price > this.price) { super.setChanged();// 设置价格改变了,设置变化,并通着观察者 super.notifyObservers(price); } this.price = price; } }