码迷,mamicode.com
首页 > 其他好文 > 详细

很有用的观察者设计模式

时间:2014-11-10 13:29:58      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:http   color   ar   os   java   sp   div   on   2014   

 

[代码][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    

bubuko.com,布布扣

 

很有用的观察者设计模式

标签:http   color   ar   os   java   sp   div   on   2014   

原文地址:http://www.cnblogs.com/steven9801/p/4086792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!