zoukankan      html  css  js  c++  java
  • java之观察者模式

    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);
        }
    }

  • 相关阅读:
    hdu4277 暴力
    hdu4271 Find Black Hand 2012长春网络赛E题 最短编辑距离
    poj3356 字符串的最小编辑距离 dp
    HDU4267 A Simple Problem with Integers 线段树/树状数组
    树链剖分 模版
    SPOJ375 Query on a tree 树链剖分
    Orz_panda cup I题 (xdoj1117) 状压dp
    27号的十道离线线段树
    The 2015 "Orz Panda" Cup Programming Contest
    codeforces #274 C. Riding in a Lift dp+前缀和优化
  • 原文地址:https://www.cnblogs.com/vonk/p/3912686.html
Copyright © 2011-2022 走看看