观察者模式是一个颇有意思的模式,该模式中有观测者和被观察的对象。java
例如:网店卖书,当书的价格产生变化时,会通知会员该书已经降价。其中书本是被观察的对象,会员是观测者。ide
BookClass:this
public class Book extends Observable { private float price; private String name; public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void modifyPrice(float price,String arg){ this.price=price; setChanged(); notifyObservers(arg); } public void showPrice(){ System.out.println("price is:"+this.price); } }
customer:code
public class Customer implements Observer{ @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub Book book=(Book)o; System.out.println("----------用户通知-----------"); System.out.println("该书降价为:"+book.getPrice()); System.out.println("消息:"+arg.toString()); } }
客户端类:server
public class mainfunction { public static void main(String[] args) { // TODO Auto-generated method stub Book book=new Book(); Customer b=new Customer(); book.addObserver(b); book.setPrice(22.3f); book.showPrice(); book.modifyPrice(44.4f, "该书降价10天"); book.showPrice(); } }
运行结果以下:对象
price is:22.3
----------用户通知-----------
该书降价为:44.4
消息:该书降价10天
price is:44.4
继承
java util类中提供了,观测者模式所须要的Observable类 和 Observer 接口,被观察的对象须要继承Observable类,观察者对象须要实现Observer接口。接口