Before we start, you might ask:
What is a design pattern?
Design pattern is a general solution to particular problem that is occurring commonly. However this is not an already implemented source code (you’ll have to do that yourself). It is not an already finished design either. You can incorporate design patterns into your application design.
It formalizes best practices and describes interactions between objects and classes. Basically it is a template for how to solve a problem.
If you want to get a better description of what a design pattern is, you can read about it on Wikipedia
It is a one-to-many push type design pattern, in which an object (“Subject”) maintains a list of dependants (“observers”). Once the subject changes state, it automatically notifies each observer with its new state.
You can think of it as a mailing list. Mailing list is the subject, you attach to it by sending in your e-mail address. But there can be many subscribers - Observer pattern does not limit the number of observers.
When there is a new email, the state has changed and the server emails it to each of the subscribers, including you!
Let’s build our own simple application that uses the Observer pattern. In this example we’re going to use PHP.
There will be at least 2 classes - one for the Subject, one for the Observer.
The Subject will have to have at least these three methods:
Attach- a method that the observers will use to register
Detach- observers may want to unregister
Notify- This will change subject’s state
As for the Observer, we can get away with this single method:
Notify- Notification method, which will be called by the subject
Ok, let’s start coding! Let’s start by creating a
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Ok, we’ve implemented our
Observers will register through
attach method and unregister through
detach method. Notifications will be sent with
Now let’s build our
1 2 3 4 5 6 7 8
Observer class only needs
notify method, which will output all received messages.
And lastly, let’s create our demo program that makes use of these classes:
1 2 3 4 5 6 7 8 9 10 11 12 13
If we run this, we should see
Can you see me? text. If you do - good work! Now you know the Observer pattern.
I’ve created a Github repository with complete code from this article.