Design Pattern Examples

The experiments discussed in this chapter involve a total of seven design patterns, sometimes in combination: Abstract Factory, Bridge, Compositum, Decorator, Observer, Template Method, and Visitor. Observer is a nice one to discuss in some detail; the rest will be characterized briefly. Exact specifications appear in [Gamma et al. 1995].

The Observer pattern solves the following design problem. Suppose an application contains an important data structure that is updated repeatedly. This data structure is called the subject. Suppose furthermore that there are a number of other components that need to be informed whenever the subject changes. These are called observers, because they watch the changes to the subject. An important aspect is that it is unknown how many observers there will be: observers should be independent and be able to come and go. This aspect precludes bundling the subject with the observers into a single class or module. Instead, there must be a dynamic link between subject and observers. The solution to this design problem is as follows: Both subject and observers are independent objects, and observers interested in a subject must register at the subject. When the subject changes, it sends a message, or an alert, to all registered observers. An example of the Observer pattern is a blog that readers might be interested in. Rather than monitoring the blog continuously, readers register at the blog and receive an alert—for example, an email ...

Get Making Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.