zoukankan      html  css  js  c++  java
  • 很有用的观察者设计模式

     

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

     

  • 相关阅读:
    适配器模式—对象适配器模式
    状态模式
    抽象工厂模式、反射
    Spring日记_01 之 Maven搭建
    既有e^x又有sinx或cosx的积分题的解法
    printf的执行顺序
    C++ 冒泡排序、选择排序、快速排序
    神舟战神 HotKey 主面板无法打开? Fn+Esc失效?
    PyCharm 和 IntelliJ IDEA的破解激活 、添加文件头注释
    单片机 之 超声波测距
  • 原文地址:https://www.cnblogs.com/fx2008/p/4086792.html
Copyright © 2011-2022 走看看