Design Patterns: Observer

After reading this book, I did learn a lot of new stuff about Design Patterns. At the same moment we are learning a lot about these patterns. One of them is Observer. It’s something I really like, and that is the reason I want to blog about it.

What is observer?

Observer is a Design Pattern to achieve the following: A broadcast (something) that notifies everyone who listens to it. When it broadcasts a change in himself, it might be possible that the listeners update themselves.

Below a little scheme to make you understand!

[ad#Adsense]

A little example to understand the scheme

The something that can be observed, is a model that saves the state from a traffic light. It can be green, orange or red. The observer or listener, could be a window that shows a square, filled with green, orange and red.

Each time that the (let’s call it model, but we refer to our traffic light) model changes his colour, we want our view to be updated.

And now, the design pattern.

Observable

This is the class that keeps a list from all the Listeners. Also it provides a method to update, add or remove an observer.

Iobserver

This is a simple interfaces that keeps has an update method. Every view, or observer needs to implement this observer.

Summary

Observer is a way (a pattern) to make things update automatically when their reference, or class that has the current state, changes. Why would we use this? The process doesn’t consumes much hardware resources. And it changes instant, when the model changes.

Do not understand it completely? Check out an example of this! It’s easy!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.