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

    package object;
    
    import java.util.Observable;
    import java.util.Observer;
    
    /**
     * @author dayu
     * @date 2019/03/04
     * @Describe 观察者模式
     */
    public class ObserverDemo {
        public static void main(String[] args) {
            Human humanA = new Human();
            Human humanB = new Human();
            Human humanC = new Human();
            
            Hourse hourse = new Hourse(80000.00);
            hourse.addObserver(humanA);//必须手动设置观察者
            hourse.addObserver(humanB);//设置观察者
            hourse.addObserver(humanC);//设置观察者
            
            hourse.setPrice(1000.0);//设置降价,观察者无反应
    //        hourse.setPrice(1000000.0);//涨价,观察者,有反应
            
        }
    }
    
    // 所有的观察者必须实现Observer 
    class Human implements Observer {
        // 如果观察的事一旦发生变化,通知
        @Override
        public void update(Observable o, Object arg) {
            if (o instanceof Hourse) {
                if (arg instanceof Double) {
                    System.out.println("房价上涨了" + arg);
                }
            }
        }
    
    }
    
    //被观察者必须继承Observable
    class Hourse extends Observable {
        private double price;
    
        public Hourse(double price) {
            this.price = price;
        }
    
        public double getPrice() {
            return price;
        }
    
        public void setPrice(double price) {
            if (price > this.price) {
                super.setChanged();// 设置价格改变了,设置变化,并通着观察者
                super.notifyObservers(price);
            }
    
            this.price = price;
        }
    
    }
  • 相关阅读:
    lintcode491 回文数
    lintcode514 栅栏染色
    lintcode433 岛屿的个数
    lintcode142 O(1)时间检测2的幂次
    lintcode166 链表倒数第n个节点
    lintcode539 移动零
    lintcode: Check Sum of Square Numbers
    lintcode: Missing String
    lintcode 二叉树的锯齿形层次遍历
    Mysql 游标的定义与使用方式
  • 原文地址:https://www.cnblogs.com/dayu007/p/10472217.html
Copyright © 2011-2022 走看看