The simplest Observer design pattern example

A few days ago I got involved in a chat about the usage of Object-oriented design patterns. I brought up the problematic of their usage when not needed, that ends up in adapting the code to the pattern and altering it, risking to increase its complexity. I mentioned an example of usage of the Observer design pattern, that I’ve seen used even where one object A (Subject) just needed to keep an array of reference of objects B (Observers), but B didn’t actually need to refer back to A.

From Wikipedia: The 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.

In this post, I’ll expose a case where the usage of that pattern is very simple to understand: a Newsletter system, with senders (Subject) and subscribers (Observers).

In this example, we have two users, John and Mike who both subscribe to the NewsletterSender (Subject). When the email is sent, both are notified by NewsletterSender::notifySubscribers() that iterates the users and call their update() passing its reference. Via this reference, the users will then be able to call the getter to read the email. So, John and Mike will both receive the reference to the NewsletterSender, John will print out the email text, but Mike only decides to say that there is an email (different implementation).

See the comment near each method with the classes and method names of the corresponding PHP interfaces SplObserver and SplSubject