Observer pattern

ObserverPattern

Observer pattern

Today, I will try to present a observer pattern.It is part of behavioral patterns and is relatively simple so I think it’s worth it to present.

Observer pattern
source : here

Subject – the object of which we want to obtain information

Observer – objects pending notification of the change in the observed object


When we use it?

When we have object(subject) that performs an operation and we want to inform other objects about the result of this operation. Then we can implement observer pattern.

I will show you how it works on the example.

Example

In our example will use price list as Subject. It will have users as observers and will inform them(users) about changing prices.

The first thing we need to do is to implement two interfaces Observer and Subject

Our interface ISubject be able to add, delete, notify observers and has a property with the current price.

Observer(listener) will update the data in our case the current price from price list.

Class PriceList looks like this:

Our class price list has list of object that will observe the object of this class.

Class User:

Class user receives two parameters User Name and references to the observed object. The method updateData displays the user’s name and the current price .

Therefore, let us see how our pattern works.

Result:

Observer pattern

Summary

As we have seen implementation observer patter is simple. If we think about it, this pattern may have a lot of applications.

Link to the project : HERE

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *