In this video Emmanuel Henri explains the observer pattern with an example.
- [Instructor] In this chapter, we'll explore all kinds of patterns related to behaviors in our applications, and we'll start with the observer pattern. But please be aware that in some cases, the patterns explored are complex to implement, and therefore, we'll demonstrate through visuals or code already built, so you understand what they are. The observer pattern is one where we maintain a list of objects, based on events, and is typically done with updating data based on events. It is implemented for example with the subscribe and publish methods in MeteorJS.
So let's take a look at code to see how it looks like. So in the exercise files, go to chapter 4 and then 04_01, and open up those two files. Or you can simply drag and drop this folder inside of Visual Studio Code. And let's take a look at the code here. So again, looking at the car class that we've used throughout this course, we are setting up a gas constructor. And then inside of that class, we have also a method that's setGasLevel, and then register and unregister through observers.
And then this notifies if anything happens with the gas. And then through a class consumption we update the car gas. So this is a perfect example of how we would use the observer pattern, and this is similar to subscribe and publish methods on Metor. So if we go to a webpage, let's go to MeteorJS. And let's go into the documentation.
And then search for publish and subscribe in the search. And if you take a look at this pattern, it's basically fitting of what an observer pattern is, because right now we are publishing to rooms and if you scroll down to the subscribe. Then we are subscribing to all players, so if we had something that published players, we would subscribe to allPlayers. So we are basically observing the allPlayers and updating it, and as we update it, then we are subscribing to it, and therefore getting data back from it.
So this is a good example of how the observer pattern is implemented into a library.
- What's a pattern?
- What's the role of callbacks?
- Creational patterns, including Singleton and Factory
- Structural patterns, including model-view-controller
- Behavioral patterns, including Memento and Mediator