Design Patterns: Observer and Publish-Subscribe



hi welcome to visual studio tool box I'm your host Robert Greene and joining is filter pixie hey Phil hey Robert how are you great we are continuing in our series of design patterns and we've moved into the studio be just a little behind the scenes we're taking us over the course of two days to this yesterday we did five of what we think is going to be wind of being 10 episodes yes and then we are here for the second day in the smaller studio different shirts different shirts two different environment more danceable chairs is that more comfortable but I think in the in the order of things one of the episodes that we taped yesterday is going to wind up being after this one yes so it'll be some back and forth well that's a TARDIS time effects though yeah exactly today we're talking about the observer pattern we are and we will also talk a little bit about publish/subscribe yeah I mean they're a lot of times they're similar whether used interchangeably a lot academically they are different so we're going to talk about that the code samples are all about the observer right most people don't write their own pub/sub they're using something like any service boss or yeah there's something along those on medication heads or something right you know you didn't have to write your own pub/sub plumbing right so let's jump into the definition again we're leveraging Wikipedia for this so the observer pattern has an object typically called the subject maintains a list of observers and notifies them when any state changes using by easily by calling a method called notify update the biggest problem with the observer pattern is memory leaks so in dotnet I'm going to have to have a strong reference to each of those observers if that observer gets set to null outside of the subject to subject will not let it go so even though you can't access it in your own code outside of the subject and it's still in the list will never be garbage collected and there's s the does that happen a lot we have to worry about that or is it just an edge case you need to bear in mind well so it does happen there's a lot of documentation out there about events and delegates and how they hold strong references hmm but fortunately I'm going to show you a solution in dotnet using a weak reference class okay that gets past the problem okay all right so let's look at the code again we're driving most of the screw unit testing so if you haven't seen our episode on unit testing they kicked this whole series off go ahead hit pause we'll wait okay that's welcome back so we have a subjective through sports aggregator I know you're a big baseball fan so I wanted to come up to the understatement come up with a Baseball Reference so the subject is just going out there and gathering information wherever it could where we can about gaming sporting events okay and then it will take the list of observers in this case I've got a newspaper and a radio station and they subscribe to the service okay so we register that register them as an observer results with the Reds beating the Cubs and oh man because we're in anything they're not this yeah that's true we're doing but we we are having some struggles with starting pitching we add a game result to the subject so however that happens it's not really part of the pattern it's just the subject gets a new game results somehow that's going to trigger the notifying and what we want to do is make sure in our tests that we still have the observers in they've gotten notified they received the game score so we make sure that they have the game results in their list and then we unregister the observers we have to specifically say I'm not paying for the service anymore okay and that's the only way we can free them up and then we just check to make sure that the observers are zero so let's look at how we code this we have a very simple interface because we always want to program to an interface and it's just I subject for lack of a more creative name and then we're going to do an entire episode on that subject of interfaces yeah okay why you say that you should always program to an interface yes what does it look like when you don't and then what does it look like if you do and what does it gain you so this is the consistent side okay but let's do an episode on that you will because you keep saying that I do I did keep saying it okay all right so I can register an observer I can unregister an observer and I can notify the observers and pretty simple right so here I have my sports aggregator which implements I subject has a list of observers when the game result gets added to irrigator now I'm not holding on to them because again this is just demo code mm-hmm I just call notifying and notify simply goes through each observer one at a time and calls the update method okay now the observers also have an interface one method that we really care about which is the update and then the list of results so the newspaper gets updated it adds this game box score to the results okay now the newspaper can choose what to do with it right it's not part of the pattern that the subject sorry that the observer does anything the pattern is that it gets notified right so for example a radio station can break in and say hey breaking news the Reds beat the Cubs newspaper might have to wait til they actually print the next paper right it's the episode of paper where they can people on their website right so it's up to them when they act on it but the pattern is we need to notify them wanted now I said there is a problem with memory leaks and let me show you in this test verbally named doesn't handle null objects correctly we set it up the same way got to our sports aggregator got the news paid Asian we register those observers we then set the first observer which is a newspaper to null we force garbage collection but then we go through and we realize on this line right here that we still have an observer in the collection okay I can't unregister the observer this line won't work and it's not because it's no right so I can't force it on register the observer sorry the subject doesn't know that it's been nullified because it's still holding a strong reference so this item will live on as the subject goes on okay now time when we're coding things using delegates or events or even I notify property change which is a good example of the observer pattern when that window goes out of scope and gets closed or where the subject gets garbage collected then it will free up all those resources okay so you asked how much of a problem it is it really depends on how you code your subject if the subject is the core of your program and is around for the lifetime of your application mm-hm it's a big problem if it's just one window in a WPF application for example probably not such a big problem okay right now I did say that there's a fix for this and that's using the weak reference class within dotnet so this is something I discovered fairly recently and I think it's really cool although it's got very specific uses what a weak reference does instead of saying hey I want to hold on to a reference of this particular object and hold a weak reference and that allows garbage collection but it does change how we code the sports aggregator and those it's a list of week references of I custom observer we're registering week references as opposed to I custom observers and when we notify we have to change things a little bit we have to instead of just saying call notify because we're holding onto a list of week references we need to get the target of that week reference okay so we call try get target and this is a new feature in c-sharp six where we don't have to declare the variable before we make it an out parameter if it's null we go ahead and unregister it so we've set it to null in our calling code and we get a notification it go through and says hey I'm going to let this thing go okay because it doesn't exist anymore otherwise I just call update normally when we look at the test for this one it's the exact same test but we can unregister the week reference even though we have sets let me change this B if I screwed up little live coding here so we will sorry we're looking at the wrong test okay that's probably being live all right this is the same code huh I register a weak reference or get a weak reference back I set the observer to null mm-hmm called garbage collection but now I can unregister if I wanted to because it's the weak reference right not the actual object but it'll need to do that because the subject itself says hey the target of this weak reference doesn't exist anymore I'm going to let go of the weak reference the cut the observer has already been garbage collected memory leak solved okay cool so that's something to keep in mind as a tool if needed yeah and like I said I think it's pretty specific where you would need it if you're doing an observer pattern and your subject again is a long-lived item mm-hmm then you need to consider this okay so let's let's talk a little bit about this versus the pub/sub pattern because that in the code were we're waiting to be told that that a game as result has occurred right right so and you mentioned that I notify property changed is a classic example of the observer pattern yes so there's a difference between needing to know or needing an expectation that you do something versus a pub/sub model where I'm publishing you subscribed but you may or may not do something well maybe we should talk about the definition of the pub/sub okay so the pub/sub is a again a messaging pattern but the publishers do not send directly to the receivers there's some sort of intermediary and that can have filtering that can have routing those types of things but the publisher has no idea if it even has any subscribers which is broadcasting right and hopefully somebody picks it up if not so be it right so if we look at the just a compare contrast between the two what happened we lost the screen so we're recording blank right now to just come out I don't know hold on up there it is oh now I've unplugged it and plugged it back in there we go okay so we went in the studio so we will probably cut some of that little cut that part okay right so we want to compare and contrast very simply right so the observer pattern everybody knows each other right I know you you know me I have your cell number mm-hmm so you can text me and you know that I know that you know that I know your cell number right right and if I call you or text you the intention is that the intention it's that you're going to respond right right so like I notified property changed you've made a change in a text box I've changed a property the intention is that somebody knows about it and acts accordingly yes right it's a more direct model right the intention is that you do something about it yeah and again that intention isn't really part of the pattern but yeah that is the practical application of it right you send and receive one at a time mm-hmm so instead of I know that in texting you can have multiple recipients on a text right but this is more you text me text Walt we go through the whole list of people we're trying to organize dinner it's all wanted right yep right and it's like we've said direct communication right the pub/sub model is different in a couple ways and I think they're significant so the sender and recipients don't know each other I send out once mm-hmm it's a like a multicast delegate for example Lynette I just you send a text message or better yet you put a tweet out and I might see your tweet I might not see your tweets mm-hmm if I have filters set up and you're talking about Microsoft and something at work like you guys have a baseball game or something well I'm filtering it outside work for Microsoft right if you're talking about getting together for dinner at C star or some other awesome restaurant here in Bellevue then I want to receive that right so there's an intermediary involved right and it's a third party so that's when we talk about things like service boss or message broker those kinds of things yep and those are really the biggest differences and and again with the pub/sub you publish people have subscribed but there's no again there's no expectation I'm not writing the code with the intention that once you broadcast something or somebody has received that and then is notified it's it's the message is out there you may do something with it you may save them up and do something later on there's really you know direct or indirect or almost immediate versus potentially delayed this yes kind of the way I think about the – that yeah I found it accurate there's also something that you can add on to the pubsub which is reliable messaging to make sure that actually gets there and you're still using intermediary right but again if we just talk about the two patterns right if I'm talking to somebody directly there is kind of an expectation that you're going to do something can you meet me for dinner yes or no right as opposed to sending out a broadcasting anybody who wants to meet for dinner we're going to this restaurant at seven o'clock ranked yep so and those are the biggest differences I don't know that anybody really writes their own pub/sub because there's so many frameworks out there to do that or the observer pattern I think is very valuable to having your tool kit when you have to do that sort of one-to-one notifications yep and truth be told we do it all the time and dotnet probably without thinking about it with another pie property changed subscribing to events and those types of things right and speaking of I notify property changed now I didn't do a test for this because if you've been doing any sort of WPF or sam'l then you're familiar with this yeah right so here's the observer it subscribes to the property changed event and when that that gets fired again the expectation is we're going to do something right update the UI you know change something and that just is again driven by events so we have an event the property change event handler this is all built into the framework and it's a perfect example right out of the box of the observer pattern yeah and and when you would use it in why yes cool great all right so that's observer pattern and a little bit of pub/sub and we'll see you next time on visual studio toolbox and we will continue our discussion of design patterns thanks for listening

7 thoughts on “Design Patterns: Observer and Publish-Subscribe

  1. Full list for this series:

    0. SOLID Design Patterns (start from here): https://www.youtube.com/watch?v=agkWYPUcLpg

    1. Design Patterns: Command/Memento: https://www.youtube.com/watch?v=zRbHlDeon3E

    2. Design Patterns: Strategy: https://www.youtube.com/watch?v=QZIvlny1Onk

    3. Design Patterns: Template Method: https://www.youtube.com/watch?v=MfAvs0n9uMs

    4. Design Patterns: Observer and Publish-Subscribe: https://www.youtube.com/watch?v=72bdaDl4KLM

    5. Design Patterns: Singleton: https://www.youtube.com/watch?v=sbML3xFHRbI

    6. Design Patterns: Factories: https://www.youtube.com/watch?v=JEk7B_GUErc

    7. Design Patterns: Adapter and Façade: https://www.youtube.com/watch?v=XYa0rmRMZ1Q

    8. Design Patterns: Decorator: https://www.youtube.com/watch?v=6PPMR0GWrZQ

  2. welcome to the people page at pajenterprises.com.for people healthy? we come to service the public join us at gitbub.com and see the master teacher #pajenterprises.

Leave a Reply

Your email address will not be published. Required fields are marked *