Observer

Software design Design patterns GOF Behavioral Patterns Observer

The Observer design pattern allows the object to manage a number of observers who respond to changes of its state by calling their methods.

Motivation

Dealing with dependencies is one of the key issues in software design. Very often, several objects can depend on one specific object. E.g. a user instance in a desktop application changes its address, however, all open forms and other dialogs with this name must be notified of this change. Moreover, an external registry service, which is used to send catalogs by mail, should be notified.

From the design point of view, it's not appropriate to pollute the user object with this logic. It shouldn't know about the objects that depend on it because it would make it unnecessarily complicated and unreadable. Thanks to Observer, the user object can be shielded from these objects.

Pattern

The object being observed is referred to as Subject in the pattern. It's an abstract class containing methods for adding, removing and notifying observers. Observer depends on Subject. It inherits from the Observer abstract class and therefore implements an interface that allows it to be notified when the subject changes. Subject manages a collection of its observers at the abstract level.

The Observer design pattern – UML diagram

When the state changes, the subject calls its notify() method and doesn't care about anything else. This method is implemented in the Subject abstract class and iterates over the collection of its observers. The update() method is called on them, which makes their state consistent again.

Conclusion

The pattern is used in systems based on event processing.


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
All articles in this section
GOF - Behavioral Patterns
Thumbnail
Next article
Strategy
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!