首页 > 编程语言 > 详细

java之观察者模式

时间:2014-08-14 16:38:08      阅读:331      评论:0      收藏:0      [点我收藏+]

import java.util.Observable;
import java.util.Observer;

class House extends Observable {
    private float price;

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        super.setChanged();
        super.notifyObservers(price);
        this.price = price;
    }

    public String toString() {
        return "House [price=" + price + "]";
    }

    public House(float price) {
        this.price = price;
    }
}

class HousePriceObserver implements Observer {
    private String nameString;

    public HousePriceObserver(String name) {
        this.nameString = name;
    }

    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof Float) {
            System.out.print(this.nameString + "price changed to be: ");
            System.out.println(((Float) arg).floatValue());
        }

    }
}

public class ObserDemo01 {
    public static void main(String[] args) {
        House house = new House(100000);
        HousePriceObserver hPriceObserver01 = new HousePriceObserver("A");
        HousePriceObserver hPriceObserver02 = new HousePriceObserver("B");
        HousePriceObserver hPriceObserver03 = new HousePriceObserver("B");
        house.addObserver(hPriceObserver01);
        house.addObserver(hPriceObserver02);
        house.addObserver(hPriceObserver03);
        System.out.println(house);
        house.setPrice(594030900);
        System.out.println(house);
    }
}

java之观察者模式,布布扣,bubuko.com

java之观察者模式

原文:http://www.cnblogs.com/vonk/p/3912686.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!