loading...
Cover image for Design Pattern: The Observer Pattern

Design Pattern: The Observer Pattern

danlee0528 profile image Daniel Lee ・1 min read

The observer pattern works like newspaper subscription. There are publishers (subjects) and subscribers (observers). The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. The only thing the subject knows about an observer is that it implements a certain interface (observer interface).

Such loosely coupled designs allow us to build flexible OO systems that can handle change because they minimize the interdependency between objects.

For example, when using classes over interfaces to implement certain behaviours of subscribers or publishers, you have to subclass them. In other words, you can't add on those behaviours to an existing class that already extends another superclass [1]. This limits its reuse potential. Also, because there's ins't an interface, you can't create your own implementation that plays well with other APIs.

[1] In inheritance, the existing class from which the new classes are derived is known as the Superclass. It is also known as the parent class or base class. A subclass inherits all the members (fields, methods, and nested classes) from its superclass. A superclass cannot use the properties and methods of the subclass, but a subclass can use the properties and methods of the superclass.

Example Diagram

Discussion

pic
Editor guide