Observer Design Pattern

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
well hello internet and welcome to part 4 of my design patterns video tutorial series today we're going to talk about the observer pattern and don't worry if you're just interested in the observer pattern this video is 100% totally self-contained however if you need to brush up on basic olp principles check out the two videos that I link to above I'm going to start off with presentation format just like in previous videos and then I'm going to show you a UML diagram and then show you all the code involved in the observer pattern so when do you use the observer pattern when you need many other objects to receive an update when another object changes so for example let's say we have a subject or publisher object that is going to represent thousands of individual stocks in the stock market if you would need to send updates to multiple observers or subscribers you would use the observer pattern to do that so what is the benefit of the observer pattern well like the strategy pattern you get the benefits of loose coupling the subject or publisher doesn't need to know anything about the observers or subscribers I'm referring to them as two different things because I think publisher makes more sense but basic jargon noop concepts says that we should use subject and observers the only negative of the observer pattern is the subject or publisher may send updates that don't matter to observers that are subscribed and this is exactly what the observer pattern looks like using a UML diagram over here you have the subject and it is going to have these three methods defined being register a new observer here's an observer over here so it's going to have the capability to register new observers and in this situation we're going to save all the observers an array list also unregister which means they'll no longer receive messages from subject and also the capability to notify the observer whenever any changes are made then of course you're going to implement an interface for the main observer and then you're going to create classes that are going to implement this observer interface and in this situation we could say that this class down here is only going to be interested in the current price for IBM and this one's going to only be interested in the current price of Apple but they are all going to use the update method to update the information inside of them and the common definition for the observer pattern is a software design pattern in which an object called the subject maintains a list of its dependents called observers and notifies them automatically of any state changes that occur over here in subject usually by calling one of their methods in this situation and in most situations that method is going to be called update so let's get into the code okay I have all these lined up already so here subject Java and this is going to be an interface that we're going to create it's going to be very simple we're just gonna go public interface subject and like I said before it's gonna handle adding deleting and updating all the observers public and this is interface so we're not really going to define anything here we're gonna go public void unregister and actually one of you guys right before i sided to do this tutorial asked me to use the observer pattern with threads so first I'm going to present it in a simple way and then I'm going to present it using threads but you definitely don't need to use threads if you want to use the observer pattern has nothing to do with threads and there you go there's your subject to interface and now I'm going to come in here and use the observer Java interface or create it and it's also going to be simple public even more simple interface observer and then we're gonna go public void update and in this situation I'm gonna be playing around with stocks so I'm gonna go IBM price it's going to be a double apples price and that's not Apple spelled wrong that is their stock symbol and let's say that we're also going to pass updates in regards to Google's stock price there you go all done that's all set up so now I'm gonna create another one of these guys called stock grabber dot Java and it is going to implement the subject interface so we're going to go public class stock grabber implements subject which is the interface we just created and then it's going to give me an error message and if i zoom in here it's gonna say the type stock driver must implement the inherited abstract methods I'm gonna say sure so that's going to save me a whole bunch of time and now I'm gonna come in here remember I said I'm gonna store all of my observers in ArrayList and it's going to store a bunch of observers and I'm just going to call them observers and then I'm going to create private fields that are going to represent the current price for all these different stocks that I'm going to be playing around with here then before I get into these classes I'm going to come down here and go stock grabber create the constructor for this it's just going to define my ArrayList and of course it's going to give me an error that I need to import the ArrayList library so do that and there it is and that's all I'm going to do inside of that so now let's get into these unimplemented methods we have down here I'm going to call this new observer just to make that a little bit easier to understand and remember and I'm just going to go observers and add there's new observer I'm just adding that new observer that we're going to create here in a minute to our ray list so pretty simple stuff leave any questions or comments below if you have any questions or comments then I'm going to implement unregistered and in this situation I'm going to call this delete observer just so I know exactly what's going on with that and then I'm going to go int observer index get the index for whatever observer is being sent over here to be deleted index of and then delete observer is the guy many user there we go and just so that I know something happened here I'm going to say system out and observer and I'm going to notify here on the screen that this guy's been deleted I'm just going to observer because the ArrayList is going to put the first observer in the zero index I'm going to increment this by one just so that I get the right observer or at least it makes more sense and I'm just going to say to leave it and now that I know which observer index is going to be deleted I just need to call the ArrayList and remove and there you are so that is going to delete observers from my ArrayList so that I will no longer send them messages because that would just be silly and then notify observers going to cycle through all the observers and notify them of any price changes that occur I'm going to put this an enhanced for-loop so we're going to go observer which is the type observer is going to be the temporary holding so and observers is going to be the ArrayList and I just got to go observer and call the update method that I'm going to create here in a second and it automatically is going to put all that information in there for me so that saves me some time that's awesome then I'm going to create a couple their methods that I'm going to use later on and all the code is available underneath this video and a link so go get it if you actually want to read the comments because it's heavily commented all right so I'm going to give them the option to change prices for all the different stocks and then notify observers of any other changes that occur so double new IBM price I'm just going to say this IBM price is equal to new IBM price and then I have to go notify observer which is the method that we just created right here so this is going to notify all the observers after the price has been changed for IBM and then we're just going to do exactly the same thing for all the other stocks and we're going to be monitoring and this could easily be turned into a real world application that gets real stocks and all that stuff without any problem at all whenever I implement threads it's going to make it even easier to do that then here we're just going to go hey PL which is going to represent apple and then notify the observers and then here we're going to do the same thing for Google so if you didn't know the stock symbol for these and now you do and there we are we're done we just created that guy so now we have to create stock observer which is going to implement the observer interface that we just created pretty simple just go public class implements the observer interface there's gonna be a whole bunch of these and it's public not pubic and of course it's going to give me an error message again stock observer must implement inherited abstract method over blah blah blah and I'm just going to click on that say okay do that for me and you can do this in different ways depending upon whether you're monitoring one stock or two and that's actually going to be your homework because you guys asked me for homework all the time this situation each observer is going to monitor all three stock prices for now and then I'm going to have to use a static that's going to be used as a counter so I'll be able to attach a special number to each one of the observers I'm just going to call it that is a variety tracker of course each class is only going to have one of these that they're going to share so it works great as a counter and then I'm going to give each individual observer object that has created a special observer ID and that's not going to be stack of course and then so I can make references to the stock grabber object I'm going to private and I'm going to call it subject and refer to it as the subject interface that it implements and that's just going to provide me access to that guy so that I can run different methods public the constructor and it's going to be passed a reference to the current stock grabber object and I'm just going to store the reference of that stock grabber object in our own personal stock grabber object that's assigned to this observer and then I'm also going to give each observer its own ID I'm gonna make sure that I increment it like that which is just going to add one remember I want to refer to these observers starting with the index one even though in the ArrayList they're going to start out in the zero index and I'm just doing this so that whenever I start playing around with these it'll be easier to understand what I'm doing and when I say new observer and then just print out its observer ID number so that we know that an observers been created of course put out inside of there and this is the reason why we needed our own stock grabber object that references the main guy because we need to register or add our new observer that we just created to stock grabbers ArrayList then we get into the class that we always are going to have to create here which is update and let's just jump up here and I'm just going to paste that inside of there it's equal to IBM price that's been passed over and then in this situation they go this which is a reference to the object or the observer that we're playing with here and then after the prices have been updated for each of the observers will print the prices which is gonna print them out for us and it's upset because it doesn't exist but it will now print the prices right like that and I'm going to go system.out.print line and the first thing I'm gonna print is the observer ID so that we know that there's more than one observer there we are and then I'm going to call a new line and then say IBM plus IBM price plus put this on a new line new line Apple stock price Apple price new line Google's price and then throw in another new line and that's it we just implemented a everything we have there of course get rid of that and there we are so let's file save it and then promised you in the past we're now going to use classes that are just going to implement public static void main and then work with the objects inside of it and grab stocks that job is going to do that for us so we're gonna go to public class grab stocks public static void if anything doesn't make sense get the code it's commented and then it will make sense probably ninety percent of the questions I get are answered in the code that I reference all the time so what are we going to do here we're going to create the subject object and it will handle updating all of the observers for us as well as deleting and adding them so just go stop Raburn like that I'm gonna call it stock grabber is we would have new stock driver so it's called that constructor it's going to handle everything for us of course that's this guy over here stock grabber implement subject okay alright so now that we have a guy that's going to go out there and get our stocks for us we need to create an observer that will be sent updates from subject or publisher whatever you want to call it so I'm just going to go observer 1 is equal to new stock the observer and I'm going to pass it stock grabber which is this guy that we just created right here so that it'll be able to access those methods that we were talking about before and now I'm going to be able to go to stock grabber set IBM price for example and come in here and go 197 copy down and we're just going to do the same thing for Apple and the same thing for Google I'm sure you remember whenever I created those methods I just did it a second ago these are actually real prices I just actually checked them and if I file save that next to cute you can see here new observers been created right there and there is the observer one and then as it changes the prices each time there's a price change this observer is notified so when I BM price changes there you go and there's Apple which hasn't been changed yet but then Apple is changed and so forth and so on however it looks like we have an error here so let's jump over and see what it is I forgot to print it out not a big deal so copy paste inside of there and then just change this to goog I'll save it awesome execute and now you can see everything's been updated you can also see how it is being notified one by one so what happens if we create another observer let's do that paste that Aaron let's just call it observer to don't need to change anything else and then we're just going to go in here and make price changes again file save piece k xq and you can now see each one of them is going to be updated there's new observer there's the first pass through this is whenever the second observer is created and you can see one by one they are automatically changed right there on the fly so that's pretty cool you can also say that if i go stock grabber unregister observer one for example if i'll save it and execute it boom and you can see right there observer one is deleted and after it's deleted it no longer receives updates that's pretty cool so now i'm going to show you how to use threads within an observer pattern which is a pretty common thing to occur and to do that i'm gonna go to get the stock dot java start working with this guy and i'm also going to do a review here kind of to a certain extent decimal format let's see if i can do this because i'm improving this that's important okay so i know i need to format the decimal as you're gonna see here in a second so this is totally improved but i should be able to do it and this is gonna allow you to use threads so we're gonna implement runnable and this is just gonna allow me to use threads without having to waste my extend so that i'll be able to use more than one class using the runnable interface so that's pretty cool then i'm gonna go well actually i'm going to show you something here um let's say that i wanted to set it so that the thread is updated based off of a start time that i define i could do it this way I'm gonna have my stock which is gonna be the name for the stock and I'm also gonna have a price that's what each of these threads is gonna have I'm gonna need a reference to stock grammar so that I'll be able to call its methods I'm gonna store a reference to stock grabber inside of there I'm gonna go get the stock so whenever this is called it's going to receive a reference to stock grabber um if I wanted to go new start time which is going to represent how long the weight before the thread is executed so how often to change the price and I could guess during I'm of course going to need whatever the stock is or stock name is and I'm also going to need the price so then I'm going to go this stock grabber just like we did before mast or reference to the stock grabber objects that's being used over in grab stock stock Java and then if I wanted to set the start time of course I just go new start time pretty easy but in this situation I'm not going to do that because I just think it's added information I'm going to go stock is equal to new stock and I'm gonna go price is equal to new price and then of course since this is implementing the runnable interface well this guys up here is complaining I knew this already but what's it gonna be complaining about it's gonna say type get the stock must implement the unheralded abstract method which is going to be run of course and there's run down there this is fun to do this I don't know if you guys like when I improv and just write code out of my head but I definitely enjoy it so I'm going to go create a for loop and let's say that I want to create new prices or change the price is 20 times well that's what that's going to do now since I'm using this interface to pause it for two seconds that's what that guy does it's going to pause it so that it waits two seconds before it executes the code that I have down below and right here if you wanted to make this change this is where you would do that you'd do something like paste that in there and multiply this and then go in and change that to 1,000 that would allow you to change how long the program waits before it executes which I've shown many times before and then I'm going to cheat here catch in a relative to exception II and I'm just gonna cheat like I said just put that in there I know that's bad and then I'm going to create a double random number and I'm going to say something random because what I want to do here with this is I want to have it kick out a value for random that's going to be between negative three cents and positive three cents well to do that you know multiply it times what you want to create here so that's going to be 0.06 and then the result of that you're going to subtract 0.03 that's how you're able to get negative random numbers and then I'm going to need decimal format I don't know if I imported that above or not yes yes I knew I needed to do that and this is just going to make sure that it comes out using only two digits so I'm going to come in here and put that there and define dollars on such is going to require it to have only two decimal places as well as one individual dollar up here so that's all that is simple stuff and then I'm going to go price is equal to well whenever you use decimal format it's going to kick out a string so we need to convert it back into a double so I'm going to go value of and I'm going to go D F format and then I'm going to take price and add to it whatever the random number is that's pretty cool oh there we go alright so now I have to call the update for each into the individual stocks and I'm thinking there's a better way to do this but right now sort of blanking so I'm just going to say if the stock name is equal to IBM I'm gonna call stock grabber set IBM price and I'm going to send it the price like that and it's giving me an error the reason why is set IBM price stock grabber right here I have it saved as a subject see right there however said IBM price isn't inside of subject however it is inside of stock grabber see there it is set IBM price so a big deal need to jump over here and cast it so I'm gonna go cast it to stock grabber that does contain that method and then just throw that right there and that should clear up and it did so that's nice now we're gonna do the same thing for Apple and and Google and let's say that I also want to print out a little message here I'm just playing around I'm just thinking in my head system all of this code is also gonna be in the link underneath the video so what do I get a print out here on let's say I want to print out the stock name and I also want to put a call 1 inside of there in a space let me use the format again now in this situation twice plus R + num I don't care if that's a string actually I want it to be a string then we're gonna put a space inside of there and then let's format again format and print out the random number so it's sort of like gonna be like okay this stock is down or up so many pennies I don't know let's throw in a print line just to cause it to create a new line and I think I got everything that I need um let's go back and let's find out so we're back over into grab stocks and if I want to create a thread inside of here give myself some room I'm going to create three threads so runnable call the first one get IBM is equal to new get the stock and what are we going to do we're going to come over here and what are we doing we have stock grabber in and all this other stuff so that's what we need to pass to it so that's cool so we're going to go stock grabber we're going to pass that reference to the stock grabber object passed to over there even though I'm not going to use it which is gonna represent how many seconds to wait before I change the price IBM's the name of it and one 9700 is going to be my starting off price let's copy that paste like I said it's going to create three threads using the runnable interface and I'm using the runnable interface so I don't waste my one and only extendable class option that we all get at birth so there's a piano Google and then I'm going to pass it the same price as it originally had and then of course after we create these threads we have to call for the code in run to execute so thread get IBM start and that's all this line code does is to say hey whatever is going on inside of the run method run it and there you are and let's execute it see if it works and it is working which is really cool and you can see here the observer well it's actually only printing out this second observer because remember we deleted the first one but you can see here as everything is changing with all these individual stocks it's automatically updating all of the observers so I hope you thought that was a pretty cool tutorial was a lot of fun to make can't believe I got it the first time another thing is that one of you guys out there at the last school and I provide a reference above is working on a tutorial that will cover how to create social networks like Facebook and this is a totally non sponsored free shoutout he asked me for a shout-out and I promised them I would do it about three videos ago but I'm doing it right now so if you want to check out his channel there's a link above and from now on if you guys want me to do shoutouts the way I'm going to handle them is the last person to ask for a shout-out on my most recent video gets a shout out in the next video and I'm not accepting anything for a shout out this is 100% unhhhh sponsored it's free so good luck and it's going to be pure luck of the draw from now on leave any questions or comments below or ask for shoutouts otherwise til next time
Info
Channel: Derek Banas
Views: 588,201
Rating: 4.8993535 out of 5
Keywords: Observer Design Pattern, Observer, Design Pattern Video Tutorial, Design Patterns
Id: wiQdrH2YpT4
Channel Id: undefined
Length: 22min 26sec (1346 seconds)
Published: Tue Aug 28 2012
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.