现在的位置: 首页 > 综合 > 正文

观察者模式-Observer

2017年12月03日 ⁄ 综合 ⁄ 共 752字 ⁄ 字号 评论关闭

观察者模式,又叫监听者模式。

import java.util.Observable;

/**
*
* @author tarena
* 观察者模式
*
*/
public class Product extends Observable {// 被观察
private int price = 20;

public int getPrice() {
   return price;
}

public void setPrice(int price) {
   this.setChanged();// 设置状态变化
   this.notifyObservers(price);// 通知观察者
   this.price = price;
}
}

----------------------------------------------------------------------------------

import java.util.Observable;
import java.util.Observer;
/**
*
* @author tarena
* 观察者模式
*
*/
public class PriceObserver implements Observer{
public void update(Observable o1,Object obj){
   System.out.println(" 价格更新为:"+obj);
}
public static void main(String[] args) {
   Product p = new Product();
   PriceObserver po = new PriceObserver();
   p.addObserver(po);
   System.out.println("begin");
   p.setPrice(30);
   System.out.println("end");
}

}

抱歉!评论已关闭.