觀察者模式是一個頗有意思的模式,該模式中有觀測者和被觀察的對象。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接口。接口