Observer pattern: what does the observer design pattern do?

When programming software, it is important to consider a range of aspects: The end product should not only have the desired functions, it should also have an easily reproducible source code that is as legible as possible. At the same time, the work involved should be kept as low as possible – especially when programs or program sections are designed with frequently recurring features or elements. Using what is known as GoF patterns (“Gang of Four”), a range of predefined pattern solutions exist for various problems in software design.

Besides other well-known patterns such as the visitor pattern or the singleton pattern, the observer pattern belongs to this collection of practical design patterns. When applied, they simplify programming work considerably. We explain what the observer design pattern can do, present it in a UML diagram, and cover the strengths and weaknesses of the pattern.

What is the observer pattern?

The observer design pattern – often abbreviated to observer pattern – is one of the most popular pattern templates for designing computer software. It provides a consistent way to define a one-to-one dependency between two or more objects in order to relay all changes made to a certain object as quickly and simply as possible. For this purpose, any objects that act as observer in this case can register with another object. The latter object – referred to as a subject – informs the registered observers as soon as it has changed.

As mentioned at the start, the observer pattern in one of the GoF patterns published in “Design Patterns: Elements of Reusable Object-Oriented Software” in 1994. The more than 20 pattern solutions described for software design continue to play an important role in designing and developing computer applications.

Purpose and function of the observer pattern

The observer design pattern works with two types of actors: On the one side, there is the subject – i.e. the object whose status is to be observed over the long term. On the other side, there are the observing objects (observers) that want to be informed about any changes to the subject.

Fact

A subject is typically assigned to multiple observers. However, in principle the observer pattern can also be used for just one observing object.

Without using the observer pattern, the observing objects would have to ask the subject to provide status updates at regular intervals; each individual request would be associated with corresponding computing time as well as the necessary hardware resources. The fundamental idea behind the observer pattern is to centralize the task of informing within the subject. It, therefore, maintains a list which the observers can register to join. In the event of a change, the subject informs the registered observers – one after the other – without them having to take action themselves. If an automatic status update is no longer desired for a certain, observing object, it can simply be removed from the list.

Note

Two different methods are available for informing the individual observers. Using the push method, the subject transmits the changed status together with the notification. However, this can result in issues if information is sent which the observer is unable to utilize. This problem does not occur with the alternative pull method. With this approach, the subject merely forwards the information that changes have been made. The observers then need to ask for the changed status by means of a separate method request.

Presenting the observer pattern in a UML diagram

For outsiders it can often be hard to understand the function and advantages of design patterns, like the observer pattern. To improve one’s understanding, it is a good idea to present the design pattern in graphical form. In particular, the widespread modeling language UML (Unified Modeling Language) is well-suited to this end, since it clearly visualizes the dependencies for users and application experts alike. The following abstract diagram shows the observer pattern in UML.

What are the advantages and disadvantages of the observer design pattern?

Using the observer pattern in software development can pay off in many situations. The big advantage that the concept offers is a high degree of independence between an observed object (subject) and the observing objects that orient themselves according to the current status of that object. For instance, the observed object does not need to have any information whatsoever about its observers, since the interaction is completed regardless of the observer interface. The observing objects receive the updates automatically. As a result, there are no unsuccessful requests within the observer pattern system (because the subject has not changed).

But the fact that the subject automatically informs all registered observers about any changes is not always an advantage. After all, change information is even sent if it is irrelevant for one of the observers. This can have a negative effect if the number of registered observers is very high, because a huge amount of computing time can be wasted by the observer system in this case. Another problem with the observer design pattern is that in the source code of the subject, it is often not apparent which observers are to be supplied with information.

Observer pattern: where is it used?

The observer design pattern is used in applications based on components, whose status:

  • is closely monitored by other components on the one hand, and;
  • is subject to regular changes on the other.

The typical application cases include GUIs (graphical user interfaces), which provide users with an easy-to-use interface for communicating with software. As soon as data is changed, these changes have to be updated in all GUI components – a scenario ideally covered by the subject/observer structure of the observer pattern. Even programs that work with datasets to be visualized (whether classic tables or graphic diagrams) also benefit from the design pattern structure.

In terms of the programming language used, there are no specific restrictions in principle for the observer design pattern. All that is important is that the object-oriented paradigm is supported, so that an implementation of the pattern also makes sense. Languages in which the use of the pattern is very popular include C#, C++, Java, JavaScript, Python, and PHP.

Observer pattern: usage example

How exactly the observer design pattern is implemented in the different programming languages can vary substantially. But the basic principle is always the same: A certain object or its status is made more easily accessible for a range of other objects. A practical example can be found in the observer pattern tutorial on the German website javabeginners.de, which we would like to orient ourselves on here.

In this example, a text published by the subject is displayed in the text fields of multiple observers. For this purpose, the subject class expands the observable class with the method addObserver(). This enables the addition of observers. Moreover, the method setChanged() is introduced which registers changes to the subject and, in the event of changes, invokes notifyObservers() to inform all observers.

class Subject extends Observable {
	public Subject(){
		this.addObserver(new Observer_1());
		this.addObserver(new Observer_2());
		tell("Text");
	}
	public void tell(String info){
		if(countObservers()>0){
			setChanged();
			notifyObservers(info);
		}
	}
}

In addition, the observers need an implementation of the observer interface including the method update() and two parameters: the observed object and the change in the form of an object instance (the ConcreteSubject).

class Observer extends JFrame implements Observer{
	private JTextField field;
	public Observer(){
		field1 = new JTextField("a");
		add(field);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 50);
		setVisible(true);
	}
	public void update(Observable o, Object arg) {
		field.setText((String) arg);
	}
}
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.