设计模式观察者模式

Design pattern is one of the most important but feared aspects of software engineering especially for people who are new to the topic. When I started my associate architecture course, I myself had a hard time understanding the idea of different software design patterns.

设计模式是软件工程中最重要但又令人担忧的方面之一,特别是对于刚接触该主题的人员而言。 当我开始辅助架构课程时,我自己很难理解不同软件设计模式的思想。

Main reason of difficulty in learning design pattern is that the terms which are used in the patterns are pretty hard to understand at first. As a developer, it’s easier for programmers to understand the idea from code, then those terminologies don’t seem that much complicated. So, this is a trial to blend both theory and code together.

学习设计模式困难的主要原因是,一开始很难理解设计模式中使用的术语。 作为开发人员,程序员更容易从代码中理解想法,然后这些术语似乎并不那么复杂。 因此,这是将理论和代码融合在一起的尝试。

And the first part starts with an important pattern, Observer design pattern.

第一部分从一个重要的模式开始,即观察者设计模式。

According to the Wikipedia, observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

根据Wikipedia的介绍,观察者模式是一种软件设计模式,在该模式中,称为主题的对象会维护其依赖者的列表(称为观察者),并通常通过调用其方法之一来自动将状态更改通知他们。

The definition is a bit difficult to understand if you are first-timer to design patterns. So let’s think about an example. Nowadays it’s the era of digital media. We all know about group subscriptions and notification on Facebook or any social media. So, when you’re trying to picture the Observer pattern, a Group subscription service with its group being the publisher and users as subscribers is a good way to visualize the pattern.

如果您是第一次设计模式, 那么定义将很难理解。 因此,让我们考虑一个示例。 如今,这是数字媒体的时代。 我们都知道团体订阅以及在Facebook或任何社交媒体上的通知。 因此,当您尝试描绘观察者模式时,以其组为发布者而用户为订阅者的组订阅服务是可视化该模式的好方法

Figure 1: Group subscription and notification as example of observer pattern
图1:组订阅和通知作为观察者模式的示例

You follow a group of your interest to get updates of the group. So you are a subscriber/follower of that group. Now if a post is updated, a notification from the group will appear in your timeline. You are the subscriber and the group is the publisher and the group has your profile information so that when a new post is updated, it sends you a notification. This kind of subscription mechanism is where we need observer design pattern.

您关注您感兴趣的组以获取该组的更新。 因此,您是该群组的订阅者/关注者。 现在,如果帖子已更新,则来自该群组的通知将出现在您的时间轴中。 您是订户,该组是发布者,该组具有您的个人资料信息,以便在更新新帖子时向您发送通知。 这种 订阅机制 是我们需要观察者设计模式的地方。

If you know about MVC pattern, “View” part of Model-View-Controller can be described as observer. When UI element changes state, all its dependents are notified and updated automatically.

如果您了解MVC模式,则可以将Model-View-Controller的“视图”部分描述为观察者。 当UI元素更改状态时,将自动通知其所有依赖项并进行更新。

For understanding observer we need to divide observer pattern into three parts. There are three parts of observer pattern.

为了理解观察者,我们需要将观察者模式分为三部分。 观察者模式包括三个部分

i) Subject/Publisher

i)主题/发布者

ii) Observer/Subscriber, and

ii)观察者/订阅者,以及

iii) Client.

iii)客户。

In observer pattern, we call the publisher the SUBJECT and the subscribers the OBSERVERS. Client-side means just the main function, so no need to worry about that. So we may think like :

在观察者模式中,我们将发布者称为SUBJECT ,将订阅者称为OBSERVERS 。 客户端只是主要功能,因此无需担心。 因此,我们可能会这样想:

Publishers + Subscribers = Observer Pattern.

发布者+订阅者=观察者模式。

Learning design pattern by just reading theory is a bit tough because of different terminology used in a pattern. For example in this pattern, we have subject, observer and client. It’s easier for programmers to understand the idea from code. So I will describe the pattern with code. The example code is in java, you can use any object-oriented language of your preference. Maybe later I will try to edit the article with other language code links.

仅通过阅读理论来学习设计模式就有些困难,因为模式中使用了不同的术语。 例如,在这种模式下,我们有subject观察者client 。 程序员更容易从代码中理解想法。 因此,我将用代码描述模式。 示例代码是用Java编写的,您可以使用任何您喜欢的面向对象语言。 也许以后我将尝试使用其他语言代码链接来编辑文章。

For people who are new to design patterns, please try to write it once yourself, it will do wonders for you.

对于不熟悉设计模式的人,请尝试自己编写一次,它将为您带来奇迹。

主题/发布者: (Subject / Publisher:)

In observer pattern, the publisher is known as the SUBJECT. The subject maintains a list of observers and notifies them automatically of any state changes. Subject in the Observer pattern has three tasks:

在观察者模式中,发布者称为“ 主题”。主题维护一个观察者列表,并自动将状态变化通知他们。 观察者模式中的主题具有三个任务:

i) Provide methods to register and remove observer.

i)提供注册和删除观察者的方法。

ii) Maintains a list of its observers/subscribers.

ii)维护其观察者/订阅者的列表。

iii) And notify them automatically when any state changes. The Subject broadcasts events to all registered Observers.

iii)并在状态发生变化时自动通知他们。 主题向所有注册的观察员广播事件。

As it’s going to notify the observer objects about the changes of its state, it is also called the publisher.

由于它将通知观察者对象其状态的变化,因此也称为发布者。

For the implementation, we will define an interface as Subject. Any class that implements this interface is a subject in observer pattern. And the class must define these three functions given in the code below.

对于实现,我们将 接口 定义 为Subject。 任何实现此接口的类都是观察者模式的主题。 并且该类必须定义以下代码中给出的这三个函数。

Subject Interface Code
主题界面代码

As you can see from figure 1 users subscribes to a group and gets a notification when a new post is updated. Group class in our example is the subject/publisher. So, it has to implement the Subject interface.

从图1中可以看到,用户订阅了一个组并在更新新帖子时收到通知。 在我们的示例中,小组课程是主题 / 发布者 。 因此,它必须实现Subject接口。

Figure 2. Class Diagram
图2.类图

In many books and websites, you will see that they put a generalized structure diagram with concreteSubject or concreteObserver. I found it hard as a beginner to relate so many generalized formula. So, we are keeping a class diagram here for better understanding. After completing this implementation, you should go back and check the structure figures in any book or website. It should make much more sense to you, at least that’s what I hope.

在许多书籍和网站中,您会看到它们放置了带有concreteSubject或concreteObserver的通用结构图。 作为初学者 ,我发现很难联系这么多广义公式。 因此,我们在这里保留了一个类图以便更好地理解。 完成此实现后,您应该返回并检查任何书籍或网站中的结构图。 这对您来说应该更有意义,至少我希望如此。

From the class diagram, you can see Group class implements subject interface. So Group class is now SUBJECT in this example. User class implements observer interface. So User class is OBSERVER. And Group has a list of observer object. So, User can use register and removeobervser methods to be observer of Group class. And Group class can notify observers with update method.

从类图中,您可以看到Group类实现主题接口。 因此,在此示例中,Group类现在为SUBJECT。 用户类实现观察者接口。 因此,用户类是OBSERVER。 并且Group有一个观察者对象列表。 因此,用户可以使用register和removeobervser方法成为Group类的观察者。 并且Group类可以使用更新方法通知观察者。

Now we are into the coding part. Code for Group class is given below. Code link is given at the end of the article.

现在我们进入编码部分。 组类的代码如下。 本文末尾提供了代码链接。

Group class implements Subject interface
组类实现Subject接口

Let’s break it down to understand observer pattern now. Observers can be added and removed from this list and Observer list will keep track of the object list. Here are the two methods provided by Subject class Group for use of observers.

现在让我们分解以了解观察者模式。 可以在此列表中添加或删除观察者,观察者列表将跟踪对象列表。 这是Subject类Group提供的供观察者使用的两种方法。

public void registerObserver(Observer o) {  observers.add(o);}public void removeObserver(Observer o) {  observers.remove(o);}

For now, let’s examine the last task of our subject, the Group class: notifying the observers. When a new post is posted, notifyObserver method gets the list of all the observers and through the update method sends posts to observer objects.

现在,让我们检查主题的最后一个任务,即Group类:通知观察者。 发布新帖子时, notifyObserver方法获取所有观察者的列表,并通过update方法将帖子发送到观察者对象。

public void newPost(String post) {  this.post = post;  notifyObserver();}public void notifyObserver() {  for (Observer observer : observers) {    observer.update();    //update posts for observers  }}

Now, we can tell that in observer there needs to have an update function. We will discuss about this in next section.

现在,我们可以告诉观察者需要一个更新功能。 我们将在下一节中对此进行讨论。

观察者/订阅者: (Observer / Subscriber:)

Observer is an actor class in this design pattern, sometimes its confusing as the design pattern name and actor name is the same. As these objects subscribe to the subject they are also known as subscribers. The observers are dependent on the subject. When the subject’s state changes, the observers get notified. In our case, if a new post is there, observers will be notified.

观察者是此设计模式中的一个actor类,有时它的混乱之处在于设计模式名称和actor名称是相同的。 当这些对象订阅主题时,它们也称为订阅者 。 观察者取决于主题。 当对象的状态改变时,观察者会收到通知。 在我们的情况下,如果有新职位,将通知观察员。

Observers subscribe and unsubscribe themselves to the Subject. Normally objects which are observers perform two tasks:

观察者订阅和取消订阅主题。 通常,作为观察者的对象执行两项任务:

i) Uses methods provided by the Subject to subscribe and unsubscribe as an observer.

i)使用主题提供的方法以观察者身份进行订阅和退订。

ii) Implements Observer interface to get update from Subject.

ii)实现观察者接口以从主题获取更新。

Figure: Relation between observer and subject
图:观察者与主体之间的关系

Below is the code for Observer interface, which has update function. So the objects who want to get notification of Group update must implement this Observer interface. We will get a look at how other classes use this class and method in User class description. Observer interface has just one function

以下是具有更新功能的Observer界面的代码。 因此,想要获取组更新通知的对象必须实现此Observer接口。 我们将在User类描述中了解其他类如何使用该类和方法。 观察者界面只有一项功能

Observer Interface
观察者界面

User class implements this Observer interface. So all the objects of user class will be now observers.

用户类实现此Observer 接口 。 因此,用户类的所有对象现在将成为观察者

User registers as observer using registerObserver method in Subscribe function. And User can be unregistered also from observer list of Group class calling removeObserver method. Group can update new post notification through update function.

用户使用订阅功能中的registerObserver方法注册为观察者。 而且,也可以从调用removeObserver方法的Group类的观察者列表中注销User。 群组可以通过更新 功能来更新新的帖子通知

User class becomes observer by implementing Observer interface
通过实现Observer接口,用户类成为观察者

客户/主要功能: (Client/Main function:)

Normally client code in design pattern example is actually code in main function. Its functionality depends on the implementation of the coder. Main function defines the number and type of Observers.

通常,设计模式示例中的客户代码实际上是main函数中的代码。 其功能取决于编码器的实现。 主要功能定义了观察者的数量和类型。

Here in client we create a group and take input for some users and those users subscribe to the group. When a new post is entered in the group, all the subscribed users get notification. The last user unsubscribes the group. So, next time a new post does not reach that user.

在客户端中,我们创建一个组并为一些用户输入内容,这些用户订阅了该组。 当在组中输入新帖子时,所有订阅的用户都会收到通知。 最后一个用户取消订阅该组。 因此,下一次新帖子无法到达该用户。

Main function is known as the client in design pattern tutorials

设计模式教程中的主要功能称为客户端

Main function/ Client Code
主要功能/客户代码

样本输出: (Sample Output:)

Figure 4: Output of ObserverTest Program
图4:ObserverTest程序的输出

Thank you for your patience. Hope this one gives you a better idea about the observer design pattern. Here is the code link, it’s currently in java. I will try to update the code in other languages also.

感谢您的耐心等待。 希望这能给您关于观察者设计模式的更好的主意。 这是代码链接 它当前在java中。 我也将尝试更新其他语言的代码。

If you are new to design pattern please don’t copy-paste the code, try to write the code yourself, it will do wonders to your understanding about the pattern. If you need any help or have any tips to improve my writing please let me know.

如果您不熟悉设计模式,请不要复制粘贴代码, 尝试自己编写代码 ,这会对您对模式的理解产生奇妙的效果。 如果您需要任何帮助或有任何技巧来改善我的写作,请告诉我。

Thank you for reading the article. Have a Good day.

设计模式观察者模式_观察者设计模式教程相关推荐

  1. java 观察者模式示例_观察者设计模式示例

    java 观察者模式示例 本文是我们名为" Java设计模式 "的学院课程的一部分. 在本课程中,您将深入研究大量的设计模式,并了解如何在Java中实现和利用它们. 您将了解模式如 ...

  2. java设计模式 观察者模式_理解java设计模式之观察者模式

    在生活实际中,我们经常会遇到关注一个事物数据变化的情况,例如生活中的温度记录仪,当温度变化时,我们观察它温度变化的曲线,温度记录日志等.对于这一类问题,很接近java设计模式里面的"观察者模 ...

  3. java监听设计模式(java观察者设计模式)

    今天给大家分享一下观察者设计模式(监听设计模式),该模式在很多主流得框架.源码中使用率非常高.在分享之前先给大家讲一个我们使用手机的一个场景,我们都用过手机,当我们手机来电话的时候,会有各种复杂的操作 ...

  4. 设计模式示例_状态设计模式示例

    设计模式示例 本文是我们名为" Java设计模式 "的学院课程的一部分. 在本课程中,您将深入研究大量的设计模式,并了解如何在Java中实现和利用它们. 您将了解模式如此重要的原因 ...

  5. 设计模式示例_命令设计模式示例

    设计模式示例 本文是我们名为" Java设计模式 "的学院课程的一部分. 在本课程中,您将深入研究大量的设计模式,并了解如何在Java中实现和利用它们. 您将了解模式如此重要的原因 ...

  6. java设计模式观察者模式吗_Java设计模式之观察者模式原理与用法详解

    Java设计模式之观察者模式原理与用法详解 本文实例讲述了Java设计模式之观察者模式原理与用法.分享给大家供大家参考,具体如下: 什么是观察者模式 可以这么理解: 观察者模式定义了一种一对多的依赖关 ...

  7. 设计模式 生成器_生成器设计模式的应用

    设计模式 生成器 嗨,您好! 今天,我将分享我制作的全新设计模式系列的第一个. 构建器设计模式是开发严肃的应用程序时非常有用且通用的模式. 在这篇文章中,我将提供一个很小的构建器模式框架,因此您随时可 ...

  8. Java设计模式(二):观察者设计模式

    1. 应用场景 某个实例的变化将影响其他多个对象. 观察者模式多用于实现订阅功能的场景,例如微博的订阅,当我们订阅了某个人的微博账号,当这个人发布了新的消息,就会通知我们. 2.概念 定义对象之间的一 ...

  9. 设计模式示例_代理设计模式示例

    设计模式示例 本文是我们名为" Java设计模式 "的学院课程的一部分. 在本课程中,您将深入研究大量的设计模式,并了解如何在Java中实现和利用它们. 您将了解模式如此重要的原因 ...

  10. 设计模式示例_桥梁设计模式示例

    设计模式示例 本文是我们名为" Java设计模式 "的学院课程的一部分. 在本课程中,您将深入研究大量的设计模式,并了解如何在Java中实现和利用它们. 您将了解模式如此重要的原因 ...

最新文章

  1. 微信小程序 在使用wx.request时显示加载中
  2. 【UCHome二次开发】全局变量
  3. 前端常用linux命令
  4. Linux中的cron计划任务配置详解
  5. 计算机网络工程本科培养计划,网络工程专业卓越计划本科培养方案2015版-西安电子科技大学计算机.doc...
  6. HTML第一章:初始HTML
  7. Makefile(二)
  8. 计算多项式的值(信息学奥赛一本通-T1012)
  9. 二、Python自动化运维入门(函数、模块)
  10. Windows下最快的磁盘空间分析软件——WizTree
  11. 杜鹏的个人博客 Flex使用Blazeds与Java交互及自定义对象转换详解
  12. Win10 解决电脑插入耳机没声音。
  13. Spring中如何操作JDBC
  14. 工信部、公安部、交通部:拟将自动驾驶汽车道路测试及示范应用范围拓宽至高速公路...
  15. 转:Flutter做出剑气效果
  16. column ‘_id‘ does not exis报错
  17. 表单提交-form提交和ajax提交
  18. 数据结构与算法(003):线性表-概述
  19. 尽管有节制的努力,pinterest仍保留着年轻女孩的反色情模因图片
  20. gdfghdsdhht

热门文章

  1. matlab矩阵除法用python改写
  2. 智能公交监控调度系统技术方案,等车不再等到心碎
  3. 12万字 | 2021数据安全与个人信息保护技术白皮书(附下载)
  4. 【java初学】正则表达式和敏感词汇过滤
  5. MATLAB——DEMATEL代码(转载)
  6. vi/vim替换字符
  7. 计算KL散度与JS散度的MATLAB程序
  8. android 自定义地图标注,Android中调用高德地图的自定义标记视图
  9. 关于空间计量模型中自回归系数大于1的解释
  10. Word 多级标题中的某一级的编号变为竖线