【设计模式-06】Observer观察者模式

这篇具有很好参考价值的文章主要介绍了【设计模式-06】Observer观察者模式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

简要说明

事件处理模型

场景示例:小朋友睡醒了哭,饿!

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

一、v1版本(披着面向对象的外衣的面向过程)

/**
 * @description: 观察者模式-v1版本(披着面向对象的外衣的面向过程)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    boolean cry = false;

    if (!cry) {
      // 进行处理
    }
  }
}

二、v2版本(面向对象的傻等)

/**
 * @description: 观察者模式-v2版本(面向对象的傻等)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    Child child = new Child();

    while (!child.isCry()) {
      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Observing......");
    }
  }
}

class Child {
  private boolean cry = false;

  public boolean isCry() {
    return cry;
  }

  public void setCry(boolean cry) {
    this.cry = cry;
  }

  public void wakeUp() {
    System.out.println("Waked Up!Crying.......");
  }
}

三、v3版本(加入观察者)

/**
 * @description: 观察者模式-v3版本(加入观察者)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    Child child = new Child();
    child.wakeUp();
  }
}

class Dad {
  public void feed() {
    System.out.println("Dad feeding...");
  }
}

class Child {
  private boolean cry = false;
  private Dad dad = new Dad();

  public boolean isCry() {
    return cry;
  }

  public void setCry(boolean cry) {
    this.cry = cry;
  }

  public void wakeUp() {
    cry = true;
    dad.feed();
  }
}

四、v4版本(加入多个观察者)

/**
 * @description: 观察者模式-v4版本(加入多个观察者)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    Child child = new Child();
    child.wakeUp();
  }
}

class Dad {
  public void feed() {
    System.out.println("Dad feeding...");
  }
}

class Mum {
  public void hug() {
    System.out.println("Mum hugging...");
  }
}

class Dog {
  public void wang() {
    System.out.println("dog wang...");
  }
}

class Child {
  private boolean cry = false;
  private Dad dad = new Dad();
  private Mum mum = new Mum();
  private Dog dog = new Dog();

  public boolean isCry() {
    return cry;
  }

  public void setCry(boolean cry) {
    this.cry = cry;
  }

  public void wakeUp() {
    cry = true;
    dad.feed();
    mum.hug();
    dog.wang();
  }
}

五、v5版本(加入多个观察者,采用接口的实现方式)

/**
 * @description: 观察者模式-v5版本(加入多个观察者,采用接口实现的方式)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    Child child = new Child();
    child.wakeUp();
  }
}

interface Observer {
  void actionOnWakeUp();
}

class Dad implements Observer {
  public void feed() {
    System.out.println("Dad feeding...");
  }

  @Override
  public void actionOnWakeUp() {
    feed();
  }
}

class Mum implements Observer {
  public void hug() {
    System.out.println("Mum hugging...");
  }

  @Override
  public void actionOnWakeUp() {
    hug();
  }
}

class Dog implements Observer {
  public void wang() {
    System.out.println("dog wang...");
  }

  @Override
  public void actionOnWakeUp() {
    wang();
  }
}

class Child {
  private boolean cry = false;

  private List<Observer> observerList = new ArrayList<>();

  {
    observerList.add(new Dad());
    observerList.add(new Mum());
    observerList.add(new Dog());
  }

  public boolean isCry() {
    return cry;
  }

  public void setCry(boolean cry) {
    this.cry = cry;
  }

  public void wakeUp() {
    cry = true;
    for (Observer o : observerList) {
      o.actionOnWakeUp();
    }
  }
}

六、v6版本(加入多个观察者,增加事件对象)

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 观察者模式-v5版本(加入多个观察者,增加事件对象)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    Child child = new Child();
    child.wakeUp();
  }
}

class WakeUpEvent {

  long timestamp;
  String loc;

  public WakeUpEvent(long timestamp, String loc) {
    this.timestamp = timestamp;
    this.loc = loc;
  }
}

interface Observer {
  void actionOnWakeUp(WakeUpEvent event);
}

class Dad implements Observer {
  public void feed() {
    System.out.println("Dad feeding...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    feed();
  }
}

class Mum implements Observer {
  public void hug() {
    System.out.println("Mum hugging...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    hug();
  }
}

class Dog implements Observer {
  public void wang() {
    System.out.println("dog wang...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    wang();
  }
}

class Child {
  private boolean cry = false;

  private List<Observer> observerList = new ArrayList<>();

  {
    observerList.add(new Dad());
    observerList.add(new Mum());
    observerList.add(new Dog());
  }

  public boolean isCry() {
    return cry;
  }

  public void setCry(boolean cry) {
    this.cry = cry;
  }

  public void wakeUp() {
    cry = true;

    WakeUpEvent event = new WakeUpEvent(System.currentTimeMillis(), "bed");

    for (Observer o : observerList) {
      o.actionOnWakeUp(event);
    }
  }
}

七、v7版本(加入多个观察者,增加事件对象且时间对象增加事件源)

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 观察者模式-v5版本(加入多个观察者,增加事件对象且事件对象增加事件源)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    Child child = new Child();
    child.wakeUp();
  }
}

interface Observer {
  void actionOnWakeUp(WakeUpEvent event);
}

class Dad implements Observer {
  public void feed() {
    System.out.println("Dad feeding...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    feed();
  }
}

class Mum implements Observer {
  public void hug() {
    System.out.println("Mum hugging...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    hug();
  }
}

class Dog implements Observer {
  public void wang() {
    System.out.println("dog wang...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    wang();
  }
}

class WakeUpEvent {
  long timestamp;
  String loc;
  Child child;

  public WakeUpEvent(long timestamp, String loc, Child child) {
    this.timestamp = timestamp;
    this.loc = loc;
    this.child = child;
  }
}

class Child {
  private boolean cry = false;
  private List<Observer> observerList = new ArrayList<>();

  {
    observerList.add(new Dad());
    observerList.add(new Mum());
    observerList.add(new Dog());
  }

  public boolean isCry() {
    return cry;
  }

  public void setCry(boolean cry) {
    this.cry = cry;
  }

  public void wakeUp() {
    cry = true;
    WakeUpEvent event = new WakeUpEvent(System.currentTimeMillis(), "bed", this);
    for (Observer o : observerList) {
      o.actionOnWakeUp(event);
    }
  }
}

八、v8版本(加入多个观察者,事件体系)

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 观察者模式-v5版本(加入多个观察者,事件体系)
 * @author: flygo
 * @time: 2022/7/18 16:57
 */
public class ObserverMain {

  public static void main(String[] args) {
    Child child = new Child();
    child.wakeUp();
  }
}

interface Observer {
  void actionOnWakeUp(WakeUpEvent event);
}

class Dad implements Observer {
  public void feed() {
    System.out.println("Dad feeding...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    feed();
  }
}

class Mum implements Observer {
  public void hug() {
    System.out.println("Mum hugging...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    hug();
  }
}

class Dog implements Observer {
  public void wang() {
    System.out.println("dog wang...");
  }

  @Override
  public void actionOnWakeUp(WakeUpEvent event) {
    wang();
  }
}

abstract class Event<T> {
  // 事件源
  abstract T getSource();
}

class WakeUpEvent extends Event<Child> {
  long timestamp;
  String loc;
  Child source;

  public WakeUpEvent(long timestamp, String loc, Child source) {
    this.timestamp = timestamp;
    this.loc = loc;
    this.source = source;
  }

  @Override
  Child getSource() {
    return source;
  }
}

class Child {
  private boolean cry = false;
  private List<Observer> observerList = new ArrayList<>();

  {
    observerList.add(new Dad());
    observerList.add(new Mum());
    observerList.add(new Dog());
  }

  public boolean isCry() {
    return cry;
  }

  public void setCry(boolean cry) {
    this.cry = cry;
  }

  public void wakeUp() {
    cry = true;
    WakeUpEvent event = new WakeUpEvent(System.currentTimeMillis(), "bed", this);
    for (Observer o : observerList) {
      o.actionOnWakeUp(event);
    }
  }
}

九、v9版本(java原生awt button使用的观察模式和模拟原生awt Button实现观察者模式)

1、java原生awt button使用的观察模式

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @description: 简单的一个按钮点击小例子演示java原生使用的观察者模式
 * @author: flygo
 * @time: 2022/7/19 10:20
 */
public class TestFrame extends Frame {

  public void launch() {
    Button button = new Button("press me");
    button.addActionListener(new MyButtonActionListener());
    button.addActionListener(new MyButtonActionListener2());

    this.add(button);
    this.pack();

    this.addWindowListener(
        new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            System.exit(0);
          }
        });
    this.setLocation(400, 400);
    this.setVisible(true);
  }

  public static void main(String[] args) {
    new TestFrame().launch();
  }
}

class MyButtonActionListener implements ActionListener {
  @Override
  public void actionPerformed(ActionEvent e) {
    ((Button) e.getSource()).setLabel("press me again!");
    System.out.println("button pressed!");
  }
}

class MyButtonActionListener2 implements ActionListener {
  @Override
  public void actionPerformed(ActionEvent e) {
    System.out.println("button pressed again!");
  }
}

2、模拟原生awt Button实现观察者模式

核心思路和逻辑

  • 定义事件类ActionEvent
  • 定义接口类 ActionListener和接口方法 void actionPerformed(ActionEvent e);
  • 自定义Button类,模拟按钮点击事件

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

  • 自定义监听者 MyActionEventListenerMyActionEventListener2实现接口 void actionPerformed(ActionEvent e);

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

  • main主方法程序Button添加监听者MyActionEventListenerMyActionEventListener2, 模拟Button调用点击方法buttonPressed

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 模拟Java原生awt button观察者模式
 * @author: flygo
 * @time: 2022/7/19 11:09
 */
public class ButtonObserverMain {

  public static void main(String[] args) {
    Button button = new Button();
    button.addActionListener(new MyActionEventListener());
    button.addActionListener(new MyActionEventListener2());

    button.buttonPressed();
  }
}

interface ActionListener {
  void actionPerformed(ActionEvent e);
}

class ActionEvent {
  long when;
  Object source;

  public ActionEvent(long when, Object source) {
    this.when = when;
    this.source = source;
  }

  public long getWhen() {
    return when;
  }

  public Object getSource() {
    return source;
  }
}

class Button {
  private List<ActionListener> listenerList = new ArrayList<>();

  public void buttonPressed() {
    ActionEvent event = new ActionEvent(System.currentTimeMillis(), this);
    for (ActionListener listener : listenerList) {
      listener.actionPerformed(event);
    }
  }

  public void addActionListener(ActionListener listener) {
    this.listenerList.add(listener);
  }
}

class MyActionEventListener implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
    System.out.println("button pressed!");
  }
}

class MyActionEventListener2 implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
    System.out.println("button pressed again!");
  }
}

十、v10版本(使用Lambda表达式实现回调或钩子函数)

JavaScript 中有钩子函数,其实就是观察者模式

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 模拟Java原生awt button观察者模式-钩子函数(hook)、回调(callback)、observer
 * @author: flygo
 * @time: 2022/7/19 11:09
 */
public class ButtonObserverMain {

  public static void main(String[] args) {
    Button button = new Button();
    button.addActionListener(new MyActionEventListener());
    button.addActionListener(new MyActionEventListener2());

    button.addActionListener(
        (e) -> {
          System.out.println("This is lambda listener!");
        });

    button.buttonPressed();
  }
}

interface ActionListener {
  void actionPerformed(ActionEvent e);
}

class ActionEvent {
  long when;
  Object source;

  public ActionEvent(long when, Object source) {
    this.when = when;
    this.source = source;
  }

  public long getWhen() {
    return when;
  }

  public Object getSource() {
    return source;
  }
}

class Button {
  private List<ActionListener> listenerList = new ArrayList<>();

  public void buttonPressed() {
    ActionEvent event = new ActionEvent(System.currentTimeMillis(), this);
    for (ActionListener listener : listenerList) {
      listener.actionPerformed(event);
    }
  }

  public void addActionListener(ActionListener listener) {
    this.listenerList.add(listener);
  }
}

class MyActionEventListener implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
    System.out.println("button pressed!");
  }
}

class MyActionEventListener2 implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
    System.out.println("button pressed again!");
  }
}

十一、JavaScript中的event事件

在很多系统中,Observer模式往往和责任链共同负责对于事件的处理,其中的某一个observer负责是否将事件往下传

<script type="text/javascript">
  function handle() {
    alert(event.target.value);
  }
</script>

<input type="button" value="press me" name="button" onclick="handle()" />

【设计模式-06】Observer观察者模式,MCA,# 设计模式,设计模式,观察者模式,java,Observer

十二、源码地址

https://github.com/jxaufang168/Design-Patternshttps://github.com/jxaufang168/Design-Patterns


 文章来源地址https://www.toymoban.com/news/detail-798576.html

到了这里,关于【设计模式-06】Observer观察者模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 设计模式——观察者模式(Observer Pattern)+ Spring相关源码

    类型:行为型模式 目的:当一个对象的状态发生改变时,其所有依赖者(观察者)都会收到通知并自动更新。 2.1.1 定义观察者 2.1.2 定义被观察对象 2.1.3 使用 2.2.1 观察者接口Observer 2.2.1 被观察者对象Observable 2.3.1 观察者 2.3.2 被观察者 创建型模式 结构型模式 1、设计模式——

    2024年02月06日
    浏览(37)
  • 【设计模式——学习笔记】23种设计模式——观察者模式Observer(原理讲解+应用场景介绍+案例介绍+Java代码实现)

    有一个天气预报项目,需求如下: 气象站可以将每天测量到的温度、湿度、气压等等以公告的形式发布出去(比如发布到自己的网站或第三方) 需要设计开放型API,便于其他第三方也能接入气象站获取数据 提供温度、气压、湿度的接口 测量数据更新时,要能实时的通知给第三

    2024年02月14日
    浏览(29)
  • 观察者设计模式(Observer Design Pattern)[论点:概念、组成角色、相关图示、示例代码、框架中的运用、适用场景]

            观察者设计模式(Observer Design Pattern)是一种行为型设计模式,它定义了一种对象间的一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,当主题对象状态发生改变时,通知所有观察者对象,使它们能够自动更新。 主题(Subject):主题是一个抽象类或

    2023年04月24日
    浏览(32)
  • 观察者模式(Observer)

    观察着模式是一种行为设计模式,可以用来定义对象间的一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新。 观察者模式又叫做发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者

    2024年02月14日
    浏览(28)
  • 观察者模式(Observer)

    事件订阅者者(Event-Subscriber) 监听者(Listener) 观察者 是一种行为设计模式, 允许你定义一种订阅机制, 可在对象事件发生时通知多个“观察”该对象的其他对象。 1. 问题 假如你有两种类型的对象 :“顾客”和“商店”。顾客对某个特定品牌的产品非常感兴趣(例如最

    2024年02月12日
    浏览(28)
  • 设计模式:观察者模式

    定义 观察者模式(Observer Pattern)是一种行为设计模式,允许一个对象(称为“主题”或“可观察对象”)维护一组依赖于它的对象(称为“观察者”),当主题的状态发生变化时,会自动通知所有观察者对象。 应用场景 观察者模式适用于以下场景: 联动反应 :当一个对象

    2024年04月08日
    浏览(44)
  • 【设计模式】观察者模式

    观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为型模式的一种,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。 Subject:抽象主题(被观察者

    2024年02月13日
    浏览(37)
  • 设计模式——观察者模式

    观察者模式可以分为观察者和被观察者,观察者通过注册到一个被观察者中,也可视为订阅,当被观察者的数据发生改变时,会通知到观察者,观察者可以据此做出反应。 可以类比订阅报纸,报社就是被观察者,订阅者就是观察者,订阅者通过订阅报纸与报社建立联系,而报

    2024年02月15日
    浏览(38)
  • 设计模式-观察者模式

    观察者模式是一种行为型设计模式,它定义了一种一对多的依赖关系,当一个对象的状态发生改变时,其所有依赖者都会收到通知并自动更新。当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者

    2024年02月15日
    浏览(43)
  • 设计模式---观察者模式

    1,概念         属于行为模式的一种,定义了一种一对多的依赖关系,让多个观察者对象同时监听某一对象主题对象,这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。 在观察者模式中有如下角色: Subject:抽象主题(抽象被观察者),

    2024年02月15日
    浏览(50)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包