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

  • 相关阅读:
    26个高效工作的小技巧 z
    DevExpress控件水印文字提示 z
    c#枚举自定义,用于数据绑定。 z
    WeifenLuo.WinFormsUI.Docking"的使用 z
    解决 winform 界面对不齐 z
    WCF服务通过防火墙怎么设置
    Auto Updating the exe from a network location when application starts z
    怎样学法学?——民法学泰斗王利明教授的演讲 z
    JAVA常见算法题(十八)
    JAVA常见算法题(十七)
  • 原文地址:https://www.cnblogs.com/vonk/p/3912686.html
Copyright © 2011-2022 走看看