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

    观察者模式属于一种行为型模式。

    观察者模式定义了一种对象间的一对多的依赖关系。当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。

    菜鸟教程中的这幅图比较直观(说白了就是,目标对象中维护着一个list存放所有的观察者对象,所有的观察者对象实现同一个observer接口来实现解耦)

    下面举一个常见的气象站的例子,就是不同的人(学生,工人)收到天气预报的改变后作出相应的处理

    气象站对象(这个就相当于上图中的Subject,也就是目标对象)

    public class WeatherStation {
        
        String[] weathers = {"天晴", "下雨", "台风"};
        
        ArrayList<Person> list = new ArrayList<>();
        
        public void addPerson(Person person) {
            list.add(person);
        }
        
        
        public void updateWeather() throws InterruptedException {
            
            while(true) {
                Random random = new Random();
                String weather = weathers[random.nextInt(weathers.length)];
                System.out.println(weather);
                
                for(Person person: list) {
                    person.doSomething(weather);
                }
                
                long time = random.nextInt(501)+1000;
                Thread.sleep(time);
            }
            
           
            
        }
    }

    观察接口(也就是上图中的observer接口)

    public interface Person {
        
        void doSomething(String weather);
    }

    学生对象

    public class Student implements Person{
        
        String name;
        
        public Student(String name) {
            this.name = name;
        }
    
        @Override
        public void doSomething(String weather) {
            if("天晴".equals(weather)) {
                System.out.println(name + "该去上学!");
            }else if("下雨".equals(weather)) {
                System.out.println(name + "撑伞去上学!");
            }else if("台风".equals(weather)) {
                System.out.println(name + "不用上学!");
            }
        }
        
    }

    工人对象

    public class Worker implements Person{
        
        String name;
        
        public Worker(String name) {
            this.name = name;
        }
    
        @Override
        public void doSomething(String weather) {
            if("天晴".equals(weather)) {
                System.out.println(name + "该去上班!");
            }else if("下雨".equals(weather)) {
                System.out.println(name + "撑伞去上班!");
            }else if("台风".equals(weather)) {
                System.out.println(name + "不用上班!");
            }
        }
    
    }
  • 相关阅读:
    Vue(小案例_vue+axios仿手机app)_go实现退回上一个路由
    nyoj 635 Oh, my goddess
    nyoj 587 blockhouses
    nyoj 483 Nightmare
    nyoj 592 spiral grid
    nyoj 927 The partial sum problem
    nyoj 523 亡命逃窜
    nyoj 929 密码宝盒
    nyoj 999 师傅又被妖怪抓走了
    nyoj 293 Sticks
  • 原文地址:https://www.cnblogs.com/xtuxiongda/p/11109614.html
Copyright © 2011-2022 走看看