java設計模式-觀察者模式

來源:互聯網
上載者:User
網上商店中的商品在名稱、價格發生變化時,必須自動通知會員,Java的API為我們提供了
Observer介面和Observable類來實現所謂觀察者模式。
  Observable(可觀察者)類允許在自身發生改變時,通知其它對象(實現介面Observer,觀察者)。
  下面是一個可觀察者(產品類):
import java.util.*;
public class product extends Observable{ 
   private String name;////產品名
   private float price;////價格

   public String getName(){ return name;}
   public void setName(String name){
    this.name=name;
   ////設定變化點 
    setChanged();
    notifyObservers(name);////通知觀察者

   }   

   public float getPrice(){ return price;}
   public void setPrice(float price){
    this.price=price;
   ////設定變化點
    setChanged();
    notifyObservers(new Float(price)); 

   }

   ////以下可以是資料庫更新 插入命令.
   public void saveToDb(){
   System.out.println("saveToDb");
    }

}

下面是兩個觀察者:
import java.util.*;
public class NameObserver implements Observer{

   private String name=null;
   public void update(Observable obj,Object arg){
     if (arg instanceof String){
      name=(String)arg;
      ////產品名稱改變值在name中
      System.out.println("NameObserver :name changet to "+name);

     }

       }
   }

import java.util.*;
public class PriceObserver implements Observer{
   private float price=0;
   public void update(Observable obj,Object arg){
     if (arg instanceof Float){

      price=((Float)arg).floatValue();
  
      System.out.println("PriceObserver :price changet to "+price);

     }

   }

}
下面是測試類別:
public class Test {

   public static void main(String args[]){
     Product product=new Product();
     NameObserver nameobs=new NameObserver();
     PriceObserver priceobs=new PriceObserver();

     ////加入觀察者
     product.addObserver(nameobs);
     product.addObserver(priceobs);

     product.setName("applet");
     product.setPrice(9.22f); 

   }
}
運行結果:
C:/java>java   Test
NameObserver :name changet to applet
PriceObserver :price changet to 9.22

C:/java>

註:以上內容來自網路,本人不承擔連帶責任。
本帖轉自:http://www.java3z.com/cwbwebhome/article/article1a/151.jsp?id=288

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.