Learn Node.js design patterns, Implementing observers

In the last lesson, we introduced the observer design pattern. We also showed how we could implement the observer design pattern and have observer objects like shoppers and malls listen to observable objects like the store.

In this lesson, we’re actually going to write the code to make the observer design pattern work in our example. So, I’m in the exercise files under chapter four, under chapter four lesson nine within the star folder, and we can see that we have the changes that we just made to our index.js file. So, let’s go ahead and first make the changes that we need to make to the observers, so I’ll start with the shopper.

And in order for this to work, the shopper’s going to have to implement a method that the store can call. So, we’ll call notify, and it will give us the store name and the discount.

So, whenever a shopper has been notified of a sale, we’ll just go ahead and log that information to the console. So, we will go ahead and add this.name, the shopper, there is a sale at store name, there is a sale at store name, and then we’ll go ahead and say what the discount is.Discount percent off everything.

There we go. So, now, when the shopper’s notified, it can respond with this notify method.Let’s go ahead and add a notify method to the mall. So, the mall’s notified method will getinvoked by the observable, but it will also do something different. The mall’s notified method is going to take the store name and the discount, and is going to go ahead and add it to the array of current sales. So, the mall is keeping track of any ongoing sales as the stores announce those sales. So, now, we have to modify the store.js.

So, the store is the observable object. It’s the object that is to announce sales. Let’s start by modifying the constructor to save an array of subscribers. Let’s go ahead and add a subscribe method to the store, and we’ll go ahead and add our observer to our array of subscribers.Now, whenever we have a sale, we don’t want to just log it to the console. We want to notify every subscriber of a sale, so we can do so by saying this.subscribers.forEach so we can iterate through every subscriber.

And then, each observer will be notified. So, this.name is the name of the current store. We’re going to send that as the first argument to the notify method, and then the discount is the second argument. There we go. Let’s go ahead and see if this works. So, I’m going to come to the terminal, and I will type node index.js. We’ve announced two sales. So, Alex, Eve, and Mike have heard about the sale at Cats & Things because they’re listening for any sales at that store, whereas Sharon heard about the sale from Ins and Outs.

Our mall is saving both sales because it’s listening to both stores.

LEAVE A REPLY

Please enter your comment!
Please enter your name here