• Java设计模式(9)——观察者模式


    一、观察者模式定义

    • Observer模式是行为模式之一,它的作用是当一个对象的状态发生变化时,能够自动通知其他关联对象,自动刷新对象状态。
    • Observer模式提供给关联对象一种同步通信的手段,使某个对象与依赖它的其他对象之间保持状态同步。

    二、观察者模式的结构

    • Subject(被观察者):被观察的对象。当需要被观察的状态发生变化时,需要通知队列中所有观察者对象。Subject需要维持(添加,删除,通知)一个观察者对象的队列列表。
    • ConcreteSubject:被观察者的具体实现。包含一些基本的属性状态及其他操作。
    • Observer(观察者):接口或抽象类。当Subject的状态发生变化时,Observer对象将通过一个callback函数得到通知。

    • ConcreteObserver: 观察者的具体实现。得到通知后将完成一些具体的业务逻辑处理。

    三、观察者模式的特点

    • 侦听事件驱动程序设计中的外部事件
    • 侦听/监视某个对象的状态变化
    • 发布者/订阅者(publisher/subscriber)模型中,当一个外部事件(新的产品,消息的出现等等)被触发时,通知邮件列表中的订阅者

    四、观察者模式的缺点

    待整理

    五、Demo

    被观察者

    /**
    * @description:
    * @auther: yangsj
    * @created: 2019/3/21 17:25
    */
    public class Blog extends Observable {

    public void publishArtical(){
    Artical artical = new Artical();
    artical.setTitle("title");
    artical.setCoutent("countent");
    this.setChanged();
    this.notifyObservers(artical);
    }
    }

    观察者


    /**
    * @description:
    * @auther: yangsj
    * @created: 2019/3/21 17:28
    */
    public class User implements Observer {
    @Override
    public void update(Observable o, Object arg) {
    Artical artical = (Artical)arg;
    System.out.println("title"+artical.getTitle() + " countent" + artical.getCoutent());
    }
    }

    消息基类

    package com.nchu.observer;

    /**
    * @description:
    * @auther: yangsj
    * @created: 2019/3/21 17:24
    */
    public class Artical {
    public String title;

    public String coutent;

    public String getTitle() {
    return title;
    }

    public void setTitle(String title) {
    this.title = title;
    }

    public String getCoutent() {
    return coutent;
    }

    public void setCoutent(String coutent) {
    this.coutent = coutent;
    }
    }

    客户端调用

    /**
    * @description:
    * @auther: yangsj
    * @created: 2019/3/21 17:30
    */
    public class APP {
    @Test
    public void Test(){
    Blog blog = new Blog();
    blog.addObserver(new User());
    blog.publishArtical();
    }
    }

    六、UML类图

  • 相关阅读:
    ExtJS 4布局
    ExrJS4学习笔记1 类
    Jquery实现动态添加按钮
    ExtJs 4 MVC
    读取目录下所有目录和文件加载到TreeView
    利用List的Sort()、Find()、FindAll()、Exist()來解決一些問題
    html常用
    ExtJs3.3 TreePanel,checked节点和平常节点同时存在
    sql server 常用查询
    美女时钟网页代码
  • 原文地址:https://www.cnblogs.com/realshijing/p/10573774.html
Copyright © 2020-2023  润新知