Factory Method Pattern – Design Patterns (ep 4)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Agree, watched most of the design patterns series. has a great teaching style.

👍︎︎ 1 👤︎︎ u/Mkelly4 📅︎︎ Jan 24 2018 🗫︎ replies
Captions
it's finally time for the factory pattern if you're not already familiar with this playlist what we're doing is that we're walking through all of the patterns in this book head first design patterns one by one by one so if you're not already subscribed now's a good time to subscribe so that you won't miss the next pattern and by the way this book had first design patterns is a great book if you're new to design patterns because very pedagogical as all these images and all of the narrative and all that stuff if you're really just looking for a reference book this is not the book but if you're new to balance be sure to get this book link in the description but now factory pattern so the head first book talks about three versions of the factory pattern one the simple factory to factory method and three abstract Factory now in the book they're saying that simple factory isn't actually a design pattern and I completely agree with this and for that reason we're now actually going to talk about it because it's not a pattern and well by-proxy will probably talk about it when we're talking about the factory method pattern because it's sort of an increase in abstraction when you go from the simple factory to the factory method I'll try and remind us so we'll see what that was all about but in other words we'll talk about the factory method and the abstract Factory and in this video I want to talk about the factory method and in the next video we'll talk about the abstract Factory so without further ado let's get into the factory method so let's first start with a little bit of narrative why do we need the factory method pattern why do we need a concept called a factory why do we need such a thing as a factory now think about it this way in our code we use a lot of different objects we have classes in object oriented program we have lots of classes and we instantiate objects from these classes and then we use these objects in a bunch of different ways now when we talked about strategy pattern you could argue that what we were doing is that we were programming by wishful thinking you were saying that when I'm in this particular method let's imagine that I already had a thing that does such-and-such right instead of instead of saying that let me construct a thing here where I am the code I would say let's assume that I already have such a thing and that I am passed dancing we are some constructor or via method essentially dependency injection so the idea the dependency injection right is you can think of it as programming by wishful thinking you can think of it as that you put yourself in the situation where you say what if I already had a thing that did this and this and this so that's a way of abstracting away the construction of an object away from the place and use that particular thing but here's the thing at some point in the program that's thing that you're passing around has to be constructed if you think about it very concretely that the keyword new justinyu up your class you have to have to instantiate your classes at some point in the program in estable if we do an object-oriented programming and we're not just using static methods everywhere which by the way don't do that then we need to instantiate objects somewhere and the question is where do we instantiate them and this is what the factory pattern in general is trying to address it's trying to say when you are about to instantiate let's encapsulate that instantiation so that we can make it uniform across all places so that you can use the factory whenever you want to instantiate and the factory is responsible for instantiating appropriately now if I seem a little bit silly to create a wrapper around the keyword new because if the difference is saying new animal or calling create animal on an animal factory class then it seems like you're just substituting one line for the other and and you start to wonder what the benefit is the thing about it from these two different perspectives so a it's possible that the instantiation is actually very complex in other words it's possible that in order to instantiate an animal you might need computation you need some kind of business logic in order to determine what parameters you want to pass through this particular animal and maybe which animal you actually want to construct that's on one hand on the second hand so be it's also about polymorphism if you have a factory that wraps your your construction and if that Factory is an instance then you can swap that at runtime you can swap that instance for an instance of another factory polymorphism let's get into this in more depth let's try to be a little bit more concrete so here's what I'm saying one we're talking about factory pattern we're saying that in your system you have a bunch of classes so you have a and you have B and USC and let's assume that these classes all either inherit from some superclass or implements some interface it's call it I so in other words A's and B's and C's can be treated as the same type and it is of course I mean double dot like you can have any number of classes in your system that can be treated as the same type right that's follow the same kind of contract doesn't matter what this is right it could be like you have cap and you have dog and you have duck and then this superclass is animal so these are a bunch of animals in your system whatever now let's say then that at a particular point in your program you want to instantiate one of these things for some reason in this position of the program you want to be able to use either a and B or C and the point is that upon entering the place let's say the method upon entering the method in which this line is located you cannot from the outside or you cannot when entering here to really know which one you want to create if you knew which one you would create this is not a factory method it's not a factory problem then you would seem to use for example dependency injection you we just have seen an instance of an A or an instance of a B or an instance of a C if you knew which one you needed but if you don't know which one you need in other words if you do if you actually here one to construct that thing and going back to what we were saying before a point one if when you're about to construct this thing you actually need some kind of logic now what we mean when we say logic let's say that I'm building a National Park simulator I'm building a simulation of like a forest or whatever so so in other words might what my program will do is that will it will spawn ducks and cats and dogs and they'll jump around and do stuff within this simulation right so it's like we have some kind of system that pretends to be a part where in animals live super silly but I mean it doesn't really matter the example doesn't matter that the point is that we want to instantiate these different things and for some reason we need some logic that determines which of these things that we want to instantiate and for example the reason I'm pushing for the force the simulation example is that we could say that ok by the way I mean wild dogs and cats in the forest never mind but just following on so we could imagine that for example what you would want to do is that you want to flip right you want to randomize something non-determinism you want to randomize and then you want to say that either I want to create this thing or I want to create this thing or I want to create this thing by the way if you haven't already noticed if you've got the diverse design patterns book I hope you forgive me for completely diverging from the example that they're using so some of the examples in this book are excellent in my humble subjective opinion and some of these examples are absolutely catastrophic goals and for the factory parent chapter I just can for the life of me figure out how they would say that this is an easy-to-understand example it might just be that it's non relatable for me because so what they're talking about is that they're talking about different types of pizzas it's like New York style pizza and whatever that other and LA style pizza or something like this and maybe it's just that not being from neither New York or LA that doesn't really make any sense to me because I'm not intimately familiar with these pizza types if I was maybe that would make perfect sense but to me that's just completely confusing so I'm choosing in an example which is extremely different from the example here I hope you don't mind or you will do is that we will look at the definition and we'll look at the UML in this book back to the example in other words we were saying that we randomly want to create either an A or B or C now you could say that okay well that's silly I mean that's that's a simple piece of logic so you would just put that logic here if the number is such-and-such great this if the number is such-and-such create that if the numbers such as such great bad but you could imagine that this is only one of the places where we're doing this let's say that we had another place where we would also want to use the same kind of logic right where we highly creative so we create a stroke we create that and imagine that the logic that we're describing here like let's say let's say random creation is only actually one of the kinds of logic we want to use to create these things maybe there are actually other ways which could be for example let's say that we have some kind of balance creation where we want to use some kind of random creation but maybe we want to maintain an equal number of these as let's say every third time so in other words like we randomly create either an A or a B or C and if it happens that we create an A then we only randomize between B's and C's and it then turns out that we create a B then next time we'll create only a C and so forth and so forth I mean it's just a silly example but what I'm emphasizing is that depending on your scenario depending on what you're building you might have different business logic that determines what thing you want to create what thing you want to instantiate and that logic can be encapsulated can be built into coded into what we commonly refer to as a factory so this Factory is responsible for for holding for keeping the business logic of creation of creation of something of a particular shared type in this scenario I in the general case or when we are using a specific example it would be animal so we have a factory that's responsible for a particular creation mechanism a particular way of constructing animals so if you have two factories then you have two ways of creating animals they both create the same thing they both create the same things but they create them in different ways and here are two important points to remember they create them in different ways and I should say and or they create different subtypes so I think we need to get a little bit more concrete so what I'm think that we have sort of two things we have the things that we are creating and we have the factories that create these things so let's say that these are the things that we're creating let's use concrete names here so let's say that this was dog and this was cat and this was dark and this main class is animal sorry for being extremely sloppy I think you can follow along so you have that right these are these are the things that were creating you can think this as the daytime we want to create some kind of data we want to build some some kind of value object it doesn't at all have to be a value object but it just for the sake of the example it might be more simple to think about it that way so these are the things we're creating but then on the other hand we have another thing which is the way in which we can create these things let's remove this to say that what we can have is for example random creation actually let's call it Factory so we have the random Factory so the random factory to be explicit we could even call it random animal factory so random animal factory create animals whether at any particular point in time you will get a dog of cat or a duck entirely depends on when we call the random factory what we call create and which is a method that returns an animal what we call create animal we get back an animal whether that animal will happen to be a dog or a cat or a duck we don't know it entirely depends on with logic resides in this method and the intent in this example the intent of the random factory the random animal Factory is that this method will randomly create any of these so to think about the other let's think about the other creation Factory that we talked about so let's say that we also have something we call the balanced Factory so again I should have called these like balanced animal factory and random animal factory but because this one is called random factory I'll call this one balanced Factory so the balanced Factory has the same signature in other words it has a method that returns an animal and is called create animal but this one like this one does is that it is that it randomizes one of these the first time you call it so it has some kind of state sources so if you think about it this Factory does not have stains because it's random everytime this fact you actually have stain the balance between these different things matter so either it uses state from the world or it use a state internally so in other words the first time it's creating randomly one of these but if at any given time you have more of any one of these then whenever you call or create animal then that single that particular animal will be excluded from the randomness I mean again remember that this is only part of the example so in terms of the pattern this doesn't matter I'm just trying to find some kind of reasonable example of what could be different between these two different things so in this particular case we're making sure that upon every third creation will have an equal number of the three different types of animals where in this one will converge towards the same number so in this one over time we'll have roughly the same number of each of the different types but at any point in time it could be that it's skewed towards one or the other again just an example so I was trying to explain this without UML but you can see there were sort of slowly moving towards UML so let's actually introduce some more UML mess so we're saying that we have these two things that are factories and you probably already guessed that because I'm saying that this is a factory and this is a factory then they should share some kind of ancestry they should share some kind of a super class or interface so let's remove this divider and let's specify that interface so in this particular scenario I would probably call that animal factory and that same of course has a method that returns an animal and is cold create animal and then of course these two classes are of that time in other words they implement the interface in case it's an interface or they are of that type if it's an abstract class or if it's a class in this particular scenario probably suffice to have it as an interface and honestly this is really pretty much it this is really pretty much the factory method pattern let's look at the definition from the adverse book so in at first they say that the factory method pattern defines an interface for creating an object but let's subclasses decide which class to instantiate factory method lets the class defer instantiation to subclasses let's stick through this the factory method pattern defines an interface remember that now when we were saying interface were none necessarily meaning interface as in class interface after class this kind of thing as in the key word but we're saying interface in terms of a contract it defines a common contract with under which you can refer to this particular thing in other words it could be an interface but it could also be a superclass so the factory method pattern defines an interface for creating an object so the key point of factory method on the key point of factory plan is that in the end you want an object you don't necessarily know how you want to construct that object why you want to construct that object and what parameters you want to pass when constructing that object these are all unknowns and that's why you want to discover this is why you want to let somebody else take that decision so the factory method pattern defines an interface for creating an object but let's subclasses decide which class to instantiate and I would again I would put more into this and just say that it's not only about which class can instantiate it's also about what you actually want to pass to that class that your instantiated factory method lets the class defer instantiation to subclasses honestly I'm not entirely sure what they mean here I'm not sure if they mean that that the common ancestor defers the decision to the subclasses or whether they seem to mean that whoever is using the factory the first to these factories but since they're saying subclasses they probably mean that that the animal factory does not have to make the decision about which of the animal class and what the path to it went when instantiating could rather nice sunglasses the random factory or the balanced factory these decide which objects are constructed how and that's it so let's then clean up the mess we got on the whiteboard and let's look at the generalized UML diagram from the book so in this example they use these terms they have a product which in our case was the animal they have a creator which in our case was the animal factory the Creator creates products the animal factory creates animals then they have concrete product which in our case were cats dogs and dogs and concrete products are products or implements products and then the final piece is that they have concrete creator which in our case was the random factory or the balanced factory the random animal factory and the balanced animal factory and these of course implement or are create pores in our case the random animal factory was an animal factory and all animal factories create animals which in this case and all the general leather is a product and the subclasses of these products are actually what is being created by any of these concrete creators if you have a concrete creator that creates some kind of concrete products but in order for us to be able to use polymorphism we need to be able to treat all of the different concrete creators the same way which is when we make all of the different concrete creators be creators and since they all need to create things that might be different in type they might be able to create dogs or cats or dogs or whatever these things need to share some kind of common interface some kind of common contract and that's why the concrete products we might have many of them or product or Internet the interface product and just to go full circle with the methods here will be also the way they denote is that they mentioned that they have a factory method iron factory method and of course then a factory method here as well and of course they're not explicitly you noting that in that first book of course the super important point is that these factory methods return something of pipe product in other words return something that is of type product which in our previous example was animal so just step back a moment and think about how we design it different responsibilities between these different classes in other words what do these different classes do what are these actually responsible for so creators are math learning implies concerned with creation of some particular thing of some share the type which in this case is denote that the product so creators create product but the creators I might be abstract or it might be an interface because because the key point is that we want to use polymorphism here's actually a very good place to talk about the simple factory normal pattern that they mentioned in the book so the simple factory that they mentioned in the head first book is essentially the same UML diagram but without the Creator portion without this above proportion in other words it's a way of having concrete factories probably a single concrete factory that is responsible for the creation of products so if you just think about that for a moment that's actually a very intuitive idea so it's like whenever we are in our application and we find some piece of logic that we repeat and that logic is centered around the creation of objects of some shared type so let's say we did that random thing we randomized a number and then we create one of three types if we realize that we're duplicating that piece of code in many places it's a very intuitive idea to say are actually let's extract that into its own class and have a method for that and let's just call that method whenever we want to use this piece this randomizer logic and create one of these three objects and that's fine and dandy it's better than nothing but it's not really using the PowerPoint morphism it's not really it's really a very very small step you should could just by introducing a tiny bit more abstraction we gained much more flexibility and that flexibility essentially stem from saying that actually this notion of being able to create something of this shared type is an idea of which I could have multiple instances the idea of having some kind of strategy or some kind of way of constructing a product is it something that could marry and then varying we can we can very easily capture with with the factory pattern with a factory method pattern so essentially we're then introducing this creator we're just saying that when I extract that logic and put that into a concrete factory into a concrete Creator then I could very easily say that that is of a type so that I trivially could later create a different creator if I add a different point in time I want to use some other kind of creator going back to the discussion of responsibilities so this side over here is responsible for creation is responsible for how to create something and this side over here is just actually the stuff that we want to create so this is sort of the data that we want to produce and again it's not actually just data so perhaps it make more sense to think about it as a product but it's this kind of stuff that we want to produce and how we produce that is defined by the factories is defined by the creators what so that's a lot of repetitions have guessed that it's probably clicking now it's not please do shoot something in the comments discuss further before we wrap up let me just try to give you a slightly different example that's very similar to this but that might provide some context into when we would perhaps want to use this and here it hopefully becomes more obvious why the factory method pattern is actually very powerful and how it gives us a lot of flexibility that eliminates a lot of potential duplication and it potentially saves us a lot of time so let's say that we're building some kind of game and let's say that this game has a number of levels right so you just think about some old arcade game that you've played like the the game where you're a ship that floats around in space and a sort of asteroids appear like enter the screen then they slowly sort of travel around and you're in this ship and you can use your thrusters to move around in the space and whenever you shoot one of these asteroids they split into multiple asteroids and you don't want to get hit by asteroids but you get a point you want to avoid anything you want to split all of them and collect points in whatever it's probably very easy for you to see how the factory method pattern would apply here we have a factory that produces asteroids the game sort of progresses and as time progresses asteroids are created so you get about it this way so think about that we have a game loop I am visiting a lot of games but it's my understanding this is the common way to do it so there's some kind of iteration that goes on in the game all the time all the time and at every take read every step at every lap of this game loop we're saying we're calling a factory we have some Factory and we're calling that Factory and we say create asteroid or just think how we're sort of moving into something more general we didn't say we didn't even say create obstacle or something like that I'm just implying that you don't necessarily need to have create asteroids and create power-ups and create ladida you didn't have them all in sort of the same method but I mean it depends entirely on your design and what you're actually trying to achieve but let's say that we have let's say that we have create a stride now that's trivial and I think you can see where how what we were doing before applies you co-create asteroid maybe you're using some randomness you know so you have something like the random asteroid Factory which maybe maybe we even only have a single type which is the asteroid it doesn't matter do we just have that type and the point is that you have some property in the asteroid which is like the size of the asteroid so sometimes you get a very large asteroid and sometimes you get a very tiny asteroid you want to have some kind of dynamic nest in the game and maybe actually also you you would potentially even randomize the the position of the asteroid you would have the x coordinate and the y coordinate in the asteroid so of course we do that because you don't always want to have the same sized asteroid that's born in the same place all the time so we randomized education and we randomized the size of the asteroid but now that's fine and dandy but that's not very complex think about it this way what if then you use a factory in level 1 and then you use another factory in level 2 then you use another factory in level 3 and so forth but actually when I say another it doesn't necessarily mean that we would have we would have the level 1 Factory and we would have a level 2 factory also different types you can see how that would scale very painfully either if you have like a lot of levels or if you actually created in game that you want to be dynamic instead you can think about it this way what is the factory what if we pass some parameters to the factory and the factory uses those parameters to determine to change some of the logic of of asteroid creation so we mean we pass two things we pass the likelihood of the asteroid being big and we pass the so we didn't talk about that parameter before but we could we would have the velocity so I mean it needs to start and sort of in motion so we would have a velocity X velocity Y for example so maybe we pass another parameter which is the speed in other words let's say that in higher levels we pass a high high speed value and high likelihood of it being large and in the lower level we pass a very low value for the speed and very low likelihood of the asteroid being large in other words we've suddenly created a very nice set of classes that we can use to dynamically build very easy levels build very easy conditions where we have small asteroids that don't move very fast and the hard levels' we are able to create large asteroids and move very quickly this is just an example I mean of course you can do this any way you want but I think you're starting to see how in an ocean that's very similar to the discussion we had around strategy pattern when you find good abstractions when you find good factories and you parameterize them in good ways you suddenly need fewer types it's like you turn pipes into properties and I think factory pattern is sort of a very helpful tool in trying to move away from a sort of class explosion into a world where we have a few key classes where there's a lot of variation that can happen by simply combining them in appropriate ways and instantiating them with different properties so this is really the point about composition over inheritance so I think you can see that if you keep on pushing on this sort of game example in this sort of asteroid examples you can create a few key factories that you can use to create tons of different levels with tons of different behavior and actually very very interesting behavior and it possibly we wouldn't even need to manually instantiate all these different factories because simply for example compute the input numbers that we give to these factories based on the level number that we have your own if we're at level four number four is a multiplier that we use to compute the likelihood of the asteroid being large or the speed of the asteroid and then we just instantiate that Factory and then we suddenly have a level four which we know is more difficult than level two level three but it's less difficult than level five and I think then again you can see easily how we could have the asteroid Factory and we can have the powerup Factory and the whatnot Factory and then we just keep on moving in that direction so we're sort of parameter rising all of the portions of the system which again moves the creation logic out of these particular levels so it's not just that we don't need to have a class for level three in a class for level four it's even that even if you have the same class for all of these that class itself the level class doesn't at all need to be concerned about creation it's just passed a few classes that are factories a few classes that are responsible for creation and it just calls the appropriate method on these creation classes which we previously call that a create animal or create product all right that's it thank you very much for watching if you have any questions or comments or feel that I've misrepresented or want to help other people in trying to understand what its pattern is actually about or when it's useful please do shoot anything in the comment and if you're new to design pattern I highly recommend you to get this book it's in the description and of course please remember to subscribe so that you won't miss the next pattern from this book and finally again thank you for watching I'll see you in the next one
Info
Channel: Christopher Okhravi
Views: 361,666
Rating: undefined out of 5
Keywords: factory method pattern, factory pattern, design pattern, factory design pattern, design patterns, head first, chrokh, head first design patterns
Id: EcFVTgRHJLM
Channel Id: undefined
Length: 27min 20sec (1640 seconds)
Published: Tue May 16 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.