Reader small image

You're reading from  Advanced Python Programming - Second Edition

Product typeBook
Published inMar 2022
PublisherPackt
ISBN-139781801814010
Edition2nd Edition
Right arrow
Author (1)
Quan Nguyen
Quan Nguyen
author image
Quan Nguyen

Quan Nguyen is a Python programmer and machine learning enthusiast. He is interested in solving decision-making problems under uncertainty. Quan has authored several books on Python programming and scientific computing. He is currently pursuing a Ph.D. degree in computer science at Washington University in St. Louis, researching Bayesian methods in machine learning.
Read more about Quan Nguyen

Right arrow

Chapter 26: The Observer Pattern

We use the observer pattern when we want to be able to inform/notify all stakeholders (an object or a group of objects) when the state of an object changes. An important feature of the observer pattern is that the number of subscribers/observers, as well as who the subscribers are, may vary and can be changed at runtime.

In this chapter, we will learn about this design pattern while comparing it to a similar one we have seen in the past, known as the MVC pattern, and use it to implement a data formatter.

Specifically, we will cover the following topics:

  • Understanding the observer pattern
  • Real-world examples
  • Use cases
  • Implementation

Technical requirements

Understanding the observer pattern

When we need to update a group of objects when the state of another object changes, a popular solution is offered by the Model-View-Controller (MVC) pattern. Let's assume that we are using the data of the same model in two views; for instance, in a pie chart and a spreadsheet. Whenever the model is modified, both views need to be updated. That's the role of the observer pattern.

The observer pattern describes a publish-subscribe relationship between a single object – the publisher, which is also known as the subject or observable – and one or more objects – the subscribers, also known as observers.

In the case of MVC, the publisher is the model, while the subscribers are the views. There are other examples that we will discuss throughout this chapter.

The ideas behind the observer pattern are the same as those behind the separation of concerns principle; that is, to increase decoupling between the publisher...

Real-world examples

In reality, an auction resembles the observer pattern. Every auction bidder has a numbered paddle that is raised whenever they want to place a bid. Whenever the paddle is raised by a bidder, the auctioneer acts as the subject by updating the price of the bid and broadcasting the new price to all bidders (subscribers).

In software, we can cite at least two examples:

  • Kivy, the Python framework for developing user interfaces, has a module called Properties, which implements the observer pattern. Using this technique, you can specify what should happen when a property's value changes.
  • The RabbitMQ library can be used to add asynchronous messaging support to an application. Several messaging protocols are supported, such as HTTP and AMQP. RabbitMQ can be used in a Python application to implement a publish-subscribe pattern, which is nothing more than the observer design pattern (j.mp/rabbitmqobs).

In the next section, we will discuss when this...

Use cases

We generally use the observer pattern when we want to inform/update one or more objects (observers/subscribers) about a change that happened on a given object (subject/publisher/observable). The number of observers, as well as who those observers are, may vary and can be changed dynamically.

We can think of many cases where the observer pattern can be useful. One such use case is newsfeeds. With RSS, Atom, or other related formats, you follow a feed, and every time it is updated, you receive a notification about the update.

The same concept exists in social networking. If you are connected to another person using a social networking service, and your connection updates something, you are notified about it. It doesn't matter if the connection is a Twitter user that you follow, a real friend on Facebook, or a business colleague on LinkedIn.

Event-driven systems is another example where the observer pattern is usually used. In such systems, you have listeners that...

Implementation

The ideas described here are based on the ActiveState Python Observer code recipe (https://code.activestate.com/). There is a default formatter that shows a value in decimal format. However, we can add/register more formatters. In this example, we will add a hex formatter and a binary formatter. Every time the value of the default formatter is updated, the registered formatters will be notified and take action. In this case, the action is to show the new value in the relevant format.

The observer pattern is one of the patterns where inheritance makes sense. We can have a base Publisher class that contains the common functionality of adding, removing, and notifying observers. Our DefaultFormatter class derives from Publisher and adds the formatter-specific functionality. We can also dynamically add and remove observers on demand.

We will begin with the Publisher class. The observers are kept in the observer's list. The add() method registers a new observer...

Summary

In this chapter, we covered the observer design pattern, including many examples, such as Kivy, the framework for developing innovative user interfaces, along with its Properties concept and module, and the Python bindings of RabbitMQ (we referred to a specific example of RabbitMQ that's used to implement the publish-subscribe, or the observer, pattern).

We also learned how to use the observer pattern to create data formatters that can be attached and detached at runtime to enrich the behavior of an object. Hopefully, you will find the recommended exercises interesting.

This also marks the end of this book. Congratulations on making it to the end, and I hope that the material that's been covered has been helpful for you in taking your Python skills to the next level!

Questions

Answer the following questions to test your knowledge of this chapter:

  1. What is the main motivation for the observer pattern?
  2. How is the observer pattern different from the MVC pattern when it comes to updating other components of an application when a target component changes?
  3. How is the observer pattern implemented in the Python example of value formatters?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Advanced Python Programming - Second Edition
Published in: Mar 2022Publisher: PacktISBN-13: 9781801814010
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Quan Nguyen

Quan Nguyen is a Python programmer and machine learning enthusiast. He is interested in solving decision-making problems under uncertainty. Quan has authored several books on Python programming and scientific computing. He is currently pursuing a Ph.D. degree in computer science at Washington University in St. Louis, researching Bayesian methods in machine learning.
Read more about Quan Nguyen