java 观察者模式设计方法
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 }