java 观察者模式设计方法
2013-07-12 11:25
399 查看
1 import java.util.Observable; 2 import java.util.Observer; 3 class House extends Observable { 4 private float price; 5 public House(float price){ 6 this.price=price; 7 } 8 public float getPrice(){ 9 return price; 10 } 11 public void setPrice(float price){ 12 super.setChanged(); 13 super.notifyObservers(price); 14 this.price=price; 15 } 16 public String toString(){ 17 return "房子价格:"+this.price; 18 } 19 } 20 class HousePriceObserver implements Observer{ 21 private String name; 22 public HousePriceObserver(String name){ 23 this.name=name; 24 } 25 public void update(Observable obj,Object arg){ 26 if(arg instanceof Float){ 27 System.out.print(this.name+"观察者看到的价格:"); 28 System.out.println(((Float) arg).floatValue()); 29 } 30 } 31 } 32 public class ObserDemo { 33 public static void main(String[] args) { 34 House h=new House(1000000); 35 HousePriceObserver hp1=new HousePriceObserver("A"); 36 HousePriceObserver hp2=new HousePriceObserver("B"); 37 HousePriceObserver hp3=new HousePriceObserver("C"); 38 h.addObserver(hp1); 39 h.addObserver(hp2); 40 h.addObserver(hp3); 41 System.out.println(h); 42 h.setPrice(6666); 43 System.out.println(h); 44 } 45 }
相关文章推荐
- 设计模式 - 观察者模式(Observer Pattern) Java内置 使用方法
- java 观察者模式设计方法
- 设计模式 - 观察者模式(Observer Pattern) Java内置 使用方法
- java设计模式7.策略模式、模板方法模式、观察者模式
- java设计模式:二、观察者模式
- JAVA设计模式之观察者模式2
- Java设计模式之二 —— 工厂方法
- java设计模式之观察者模式
- Java设计模式(行为型)之-模板方法模式
- java设计模式学习(一):观察者模式(一)
- 设计模式之第3章-模板方法模式(Java实现)
- java设计模式--观察者模式 Observer
- Java设计模式之观察者模式
- 最常用的Java设计之一 观察者模式 在android中的实例 ListView Adapter机制
- 【设计模式】Java设计模式第一课之观察者模式
- Java设计模式-模板方法模式
- Java设计模式-观察者模式(Observer)
- 设计模式---观察者模式(Observer Pattern with java)
- java设计模式之观察者模式
- java设计模式入门(2)观察者模式