很有用的观察者设计模式

 

[代码][Java]代码     

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Observable;
 
public class House extends Observable {
     
    private float price;
 
    public House(float price) {
        this.price = price;
    }
 
    public float getPrice() {
        return price;
    }
 
    public void setPrice(float price) {
        super.setChanged();          //设置变化点
        super.notifyObservers(price);  //发出变化通知
        this.price = price;
    }
 
    @Override
    public String toString() {
        return "房子的价格为:" + price ;
    }
     
}

 

2. [代码][Java]代码     

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Observable;
import java.util.Observer;
 
public class Buyer implements Observer{
     
    private String name;
     
    public Buyer(String name) {
        this.name = name;
    }
 
    @Override
    public void update(Observable observable, Object object) {
        if (object instanceof Float) {
            System.out.print(this.name + "观察到价格变化:");
            System.out.println(((Float)object).floatValue());
        }
    }

 

3. [代码][Java]代码     

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class TestMain {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        House house = new House(1000f);
        Buyer b1 = new Buyer("A");
        Buyer b2 = new Buyer("B");
        Buyer b3 = new Buyer("C");
        house.addObserver(b1);
        house.addObserver(b2);
        house.addObserver(b3);
        System.out.println(house);
        house.setPrice(6000.0f);
        System.out.println(house);
 
    }
 
}

 

4. [图片] 未命名.png    

 

原文地址:https://www.cnblogs.com/fx2008/p/4086792.html