YTread Logo
YTread Logo

Factory Method Pattern – Design Patterns (ep 4)

Mar 26, 2024
finally it's time for the

factory

pattern

, if you are not already familiar with this playlist, what we are doing is going through all the

pattern

s in this book, first the

design

patterns

, one by one, so if you are not subscribed yet , now is a good time to subscribe so you don't miss the next pattern and by the way, this book had the first

design

patterns

. It's a great book if you're new to pattern design because it's very pedagogical like all these pictures and everything. of the narrative and all that, if you're really just looking for a reference book this isn't the book, but if you're new to balance make sure you get the link for this book in the description, but now the

factory

pattern, So the main book talks about three versions of the factory pattern, one the simple factory-to-factory

method

and three abstract factories.
factory method pattern design patterns ep 4
Now in the book they say that the simple factory is not actually a design pattern and I completely agree with this and for that reason we are Now let's talk about it because it's not a pattern and well the proxy will probably talk about it when we talk about the factory

method

pattern because it's kind of an increase in abstraction when you go from one simple factory to another. method I'll try to remind us so we can see what it is, but in other words, we're going to 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 one.
factory method pattern design patterns ep 4

More Interesting Facts About,

factory method pattern design patterns ep 4...

In the video we will talk about the abstract factory, so without further ado let's get into the factory method, so first let's start with a little narrative. Why do we need factory method pattern? Why do we need a concept called factory? Because we need? something like a factory now think of it this way in our code we use many different objects we have classes in an object oriented program we have many classes and we instantiate objects of these classes and then we use these objects in a group in different ways Now, when we talked about the strategy pattern, you could argue that what we were doing is that we were programming with wishful thinking.
factory method pattern design patterns ep 4
You were saying that when I'm in this particular method, let's imagine that I already had something that does such and such right, instead of saying that, let me build something here where I'm the code, I would say let's suppose that I already have such and such a thing and that they dance to me, we are some constructor or through a method essentially dependency injection, so The idea of ​​dependency injection is that you can think of it as programming through an illusion. You can think of it as putting yourself in a situation where you say: What if I already had something that did this and this and this?
factory method pattern design patterns ep 4
So that's a way of abstracting the construction of an object out of place and using that particular thing, but here's the thing at some point in the program that is the thing that you're passing in has to be constructed if you think about it very concrete that the keyword new justinyu above your class you have to create an instance of your classes at some point in the program in stable if we do object-oriented programming and we are not using static methods everywhere that by the way do not 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 that when you're about to instantiate, let's encapsulate that instantiation so we can make it consistent across all. places so you can use the factory when you want to create an instance and the factory is responsible for creating an appropriate instance now yes it seems a bit silly to me to create a wrapper around the new keyword because if the difference is to say new animal or call create animal in an animal factory class, then it seems like you're just substituting one line for the other and you start to wonder what the benefit is from these two different perspectives, so it's possible that instantiation is actually very complex in In other words, to create an instance of an animal you may need calculus, you need some kind of business logic to determine what parameters you want to pass through this particular animal and maybe what animal you actually want to build, which is for a side on the second hand, it's also about polymorphism if you have a factory that wraps your build and if that factory is an instance then you can swap it at runtime, you can swap that instance for an instance of another factory polymorphism, let's get into it on this in more detail. depth, let's try to be a little more concrete, so this is what I'm saying: we're talking about the 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 all these classes inherit from some superclass or implement some interface, it is called I, so in other words A, B and C can be treated as the same type and of course I mean double point, as if you can have any number. of classes in your system that can be treated as the same type, right, that follow the same type of contract, no matter what it is, it could be like you have cap, dog, duck and then this superclass is animal. so these are a bunch of animals in your system, whatever it is, now let's say at a particular point in your program you want to instantiate one of these things for some reason at this position in the program you want to be able to use a and B or C and the point is that when you enter the place let's say the method when you enter the method that this line is in you can't from the outside or you can't when you enter here really know which one you want to create if you knew which one you would create, this is not a method out of the box, it's not a factory issue, so it would seem like you would use, for example, dependency injection.
We just saw an instance of A or an instance of B or an instance of C if you only knew. which one you needed, but if you don't know which one you need, in other words, if you know, if you're really here to build that thing and going back to what we were saying before point one, if you're about to build. For this, you actually need some kind of logic. What do we mean when we say logic? Let's say I'm building a National Park simulator. I'm building a simulation of a forest or whatever. In other words, it could be what my program will do.
What I do is it will spawn ducks and cats and dogs and they will jump around and do things inside this simulation, so it's like we have some kind of system that's pretending to be a part where animals live super dumbly, but it I mean seriously. It doesn't really matter the example, it doesn't matter, 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 we want to create and for example the reason I'm force pressing , the simulation example is that we could say okay, by the way, I mean wild dogs and cats in the forest, it doesn't matter, but we just keep going so that we can imagine that, for example, what you would want to do is what you want . turn right you want to randomize something non-determinism you want to randomize and then you want to say I want to create this or I want to create this or I want to create this by the way if you haven't already I've noticed if you have the diverse design patterns book.
I hope you'll forgive me for completely deviating from the example they're using, so some of the examples in this book are excellent IMHO and some of these examples are absolutely catastrophic objectives and for the main factory chapter, by my life I can figure out how they would say this is an easy to understand example, it could just be that it's not relatable to me because then what are they talking about? It's just that they're talking about different types of pizza, it's like New York style pizza and every other Los Angeles style pizza or something and maybe it's just that being neither from New York nor from Los Angeles that doesn't really make any sense.
To me, because I'm not intimately familiar with these types of pizza, if I were, maybe it would make a lot of sense, but to me that's completely confusing, so I choose an example that is extremely different from the example here. I hope not. What you don't care about or what you will do is that we will look at the definition and we will look at the UML in this book going back to the example. In other words, we were saying we want to randomly create an A, a B, or a C. You might say okay, that's nonsense, I mean, it's a simple piece of logic, so you would just put that logic here if the number is such and such big, this if the number is such and such, create that if the numbers are such. as such, very bad, but you can imagine that this is just one of the places where we are doing this.
Let's say we have another place where we would also want to use the same type of logic where we are very creative, so we create a stroke, we create that and we imagine that the logic that we are describing here, like let's say, random creation, is actually just one of the types of logic that we want to use to create these things, maybe there are actually other ways that it could be, for example. Let's say we have some kind of balance creation where we want to use some kind of random creation, but maybe we want to keep an equal number of these, say every three times, in other words, we randomly create an A or a B or C and if we happen to create an A then we only randomize between B and C and then we happen to create a B then next time we will create only a C and so on, 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 may have different business logic that determines what thing you want to create, what thing you want to instantiate, and that logic can be encapsulated. integrated coded into what we commonly call a factory, so this factory is responsible for maintaining the business logic of creating something of a particular shared type in this scenario I in the general case or when we are using a A specific example would be animal, so we have one factory that is responsible for a particular creation mechanism, a particular way of building 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 be a little more concrete, so what do I think? 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 these are the things that we are creating, let's use concrete names here, so let's say this was dog and this was cat and this was dark and this main class is animal sorry for being extremely careless I think you can follow us so you're right these are these things they were creating you may think this is during the day we want to create some kind of data we want to build some kind of value object, it doesn't have to be a value object at all, but just for the example, it might be simpler to think of it that way, so these are the things that we are creating, but on the other hand we have another thing, which is the way we can create these things.
Let's eliminate 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 to be explicit, the random factory we could even call it random animal factory, so the random animal factory creates animals, whether at a certain time you get a dog, a cat or a duck, depends entirely on when we call to the random factory. create and that is a method that returns an animal what we call create animal we get back an animal whether that animal will be a dog, a cat or a duck, we don't know, it depends completely on the logic residing in this method and the intention 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 one, let's think about the other Creation Factory that we talked about, so let's say which we also have something we call Balanced Factory, so again I should have called them Balanced Animal Factory and Random Animal Factory, but since this one is called Random Factory, I will call it Balanced Factory so that Balanced Factory has the same signature, in other words , it has a method that returns an animal and it's called create animal, but this one like this makes it randomize 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 has no blobs because it's random every time this fact actually has a blob, the balance between these different things matters so it uses a state from the world or it uses a state internally, in other words the first time it randomly creates one of these, but if at any given time, you have more of any of these and every time you call or create an animal, that particular animal will be excluded from the randomness.
I mean, remember again 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 might be different between these two different things, so in this particular case we're making sure that every third creation has a equal number.of the three different types of animals where in this will converge towards the same number, so in this over time we will have approximately the same number of each of the different types, but at any time it could be that it is biased towards one or the other again just an example so I was trying to explain this without UML but you can see they are slowly moving towards UML so let's introduce more UML confusion so we say we have these two things which are factories and You probably already guessed it because I'm saying this is a factory and this is a factory, so they should share some kind of ancestry, they should share some kind of super class or interface, so let's remove this divisor and specify that. interface, so in this particular scenario you would probably call that animal factory and that same of course has a method that returns an animal and it's cold create animal and then of course these two classes are from that time, in other words , they implement the interface in case it is an interface or they are of that type, if it is an abstract class or if it is a class in this particular scenario, it is probably enough to have it as an interface and honestly, this is more or less the pattern of the factory method, let's look at the definition of the adverse book, at the beginning they say that the factory method pattern defines an interface to create an object, but let the subclasses decide which class to instantiate.
The factory method allows the class to defer instantiation to subclasses. Let's continue with this factory method pattern. defines an interface, remember now when we said interface, none necessarily meant interface like in class interface after class, this kind of thing like in the keyword, but we're saying interface in terms of a contract, it defines a common contract under which can refer to this particular thing, in other words it could be an interface but it could also be a super class, so the factory method pattern defines an interface to create an object, so the key point of the factory method in the key point of the factory plan is that in the end you want an object, you don't necessarily know how you want to build that object, why you want to build that object and what parameters you want to pass when building that object, all of these are unknown and that's why you want to discover this. that's why you want to let someone else make that decision so let the factory method pattern define an interface to create an object but let the subclasses decide which class to instantiate and again I would put more into this and just say that it's not just about what the class can instantiate, it's also about what you actually want to pass to that class, that your instantiated factory method allows the class to defer instantiation to subclasses.
Honestly, I'm not entirely sure what they mean here. I'm not sure if they mean that the common ancestor defers the decision to the subclasses or if they seem to mean that whoever is using the factory first in these factories, but since they're saying subclasses, they probably mean that the animal factory doesn't have You have to make the decision on which of the animal classes and what the path to it was when instantiated, it could be pretty nice sunglasses, the random factory or the balanced factory, these decide which objects are built, how and that's it , so then let's clean up the mess on the board and look at the generalized one.
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 a specific product which in our case were cats, dogs and dogs and the concrete products are products or implements, products and then the final piece is that they have a 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 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 leather in general is a product and the subclasses of these products are actually what is being created.
Any of these concrete creators do have a concrete creator that creates some type of concrete products, but in order for us to use polymorphism we must be able to treat all the different concrete creators the same, which is when we make all the different concrete creators are creators. and since everyone needs to create things that may be of different types, they could 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 concrete products we could have a lot of them or product or internet interface product and just to close the loop with the methods here will also be the way that they denote is that they mentioned that they have a factory method factory method of iron and of course, here there is also a factory method and of course, they are not explicitly noting that in that first book, of course, the super important point is that these factory methods return some pipe product, in other In other words, they return something that is of type product. which in our previous example was animal, so step back for a moment and think about how we designed it.
Different responsibilities between these different classes. In other words, what do these different classes do? What are they really responsible for? So creators are learning mathematics involves caring about creation. of some particular thing of some shared type which in this case denotes that the product, so the creators create the product, but the creators I could be abstract or it could be an interface because the key point is that we want to use polymorphism, here There is actually a very good place to talk about the normal simple factory pattern that they mentioned in the book, so the simple factory that they mentioned in the first book is essentially the same UML diagram but without the Creator part and without This previous proportion, in other words, is a shape. of having concrete factories, probably a single concrete factory that is responsible for creating products, so if you think about that for a moment, it's actually a very intuitive idea, it's like when we are in our application and we find some part of logic that we repeat and that logic focuses on creating objects of some shared type, so let's say we did something random, we randomize a number and then create one of three types if we realize that we are duplicating that piece of code in a lot of places where it's a very intuitive idea to say let's actually extract that into its own class and have a method for that and call that method when we want to use this piece of this randomization logic and create one of these three objects and that that's fine and dandy, it's better than nothing, but it's not really using the PowerPoint morphism, it's not really a very, very small step, you should, just by introducing a little bit more abstraction, we got a lot more flexibility and that flexibility comes essentially saying that actually this notion of being able to create something of this shared type is an idea that could have multiple instances, the idea of ​​having some type of strategy or some type of way of building a product, is something that could be combined and then, varying, we can. capture very easily with the factory pattern with a factory method pattern, so essentially we introduce this creator, we just say that when I extract that logic and put it in a concrete factory in a concrete Creator, then I could very easily say that that is of a type that could trivially then create a different creator if I add a different moment in time.
I want to use some other type of creator going back to the responsibilities discussion, so this side here is responsible for creation. responsible for how to create something and this side here is actually what we want to create so this is the data we want to produce and again it's not just data so maybe it makes more sense to think about it. as a product, but it is this type of thing that we want to produce and the way we produce is defined by the factories is defined by the creators. So, it's a lot of repetitions.
I've guessed you're probably clicking now. It is not like this. Please film something in The comments are discussed further before we wrap up, let me try to give you a slightly different example that is very similar to this one, but might provide some context for when we might want to use this and here, hopefully, it will become more obvious why the factory method. The pattern is actually very powerful and gives us a lot of flexibility which eliminates a lot of potential duplication and potentially saves us a lot of time, so let's say we're building some kind of game and let's say this game has a right amount of levels, so just You think about some old arcade game you've played, like the game where you're a ship floating in space and some sort of asteroids appear as if they enter the screen and then slowly travel away. and you're on this ship and you can use your thrusters to move in space and every time you shoot one of these asteroids, they split into multiple asteroids and you don't want to get hit by the asteroids, but you get the point you want.
To avoid anything you want to split them all up and accumulate points on 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 progresses and as time progresses, asteroids are created. So you can do it this way, so think we have a game loop. I'm visiting a lot of games, but my understanding is that this is the common way to do it, so there is some kind of iteration happening in the game all the time. all the time and in each shot read each step in each turn of this game loop we say we call a factory we have something Factory and we call it Factory and we say create asteroid or just think how are we something like moving on to something more general, We didn't say, we didn't even say create obstacles or anything like that.
I'm just hinting that you don't necessarily need to create asteroids, create power-ups, and create ladida. I don't have them all with the same method, but I mean it depends entirely on your design and what you're actually trying to achieve, but let's say we've created a step now that's trivial and I think you can see where what we were applying applies. doing before. You can co-create an asteroid, maybe you're using some randomness, you know, so you have something like the Random Asteroid Factory, which maybe we only have a single type, which is the asteroid that doesn't have.
It doesn't matter, we only have that type and the point is that you have some property on the asteroid that is like the size of the asteroid, so sometimes you get a very large asteroid and other times you get a very small asteroid that you want to have of some type . of dynamic nest in the game and maybe also you, potentially even randomize the position of the asteroid, you would have the x coordinate and the y coordinate on the asteroid, so of course we do it because you don't always want to have the asteroid the same size as it is born in the same place all the time, so we randomize the education and we randomize the size of the asteroid, but that's all well and good, but it's not very complex, think of it this way, what happens if you then use a factory in the level? 1 and then you use another factory at level 2, then you use another factory at level 3 and so on, but actually when I say another it doesn't necessarily mean that we would have the Level 1 Factory and we would have a level. 2 factories, also different types, you can see how that would escalate very painfully, whether you have a lot of levels or if you actually created in the game you want it to be dynamic, you can think of it this way, what is the factory?
We pass some parameters to the factory and the factory uses those parameters to determine changing some of the asteroid creation logic, by which we mean we pass two things, we pass the probability that the asteroid is large and we pass the then not it. we did. We talked about that parameter before, but we could have speed, so I mean it needs to start and be moving, so we would have speed X speed Y, for example, so maybe we pass another parameter which is speed, in In other words, let's say that at the upper levels we pass a high speed value and a high probability that it is large and at the lower level we pass a very low value for the speed and a very low probability that the asteroid is large in other words. , we have suddenly created a very good set of classes that we can use to dynamically build very easy levels, build very easy conditions where we have small asteroidsThey don't move very fast and in difficult levels we can create large asteroids and move very fast. 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 it's very similar to the discussion we had about the strategy pattern when you find good abstractions, when you find good factories and you parameterize them in a good way, suddenly you need fewer types, it's like converting pipes into properties and I think the factory pattern is a very useful tool to try to move us away from a kind of explosion of classes towards a world where we have some keys. classes where there is a lot of variation that can occur just by combining them appropriately and creating instances with different properties, so this is really the point about composition inheritance, so I think you can see that if you keep pushing this type of game in this kind of asteroid examples, you can create some key factories that you can use to create tons of different levels with tons of different behavior and actually very interesting behavior and we possibly wouldn't even need to manually instantiate all of these different factories because we just, For example, we calculate the entry numbers we give to these factories based on the level number we have if we are at level four.
The number four is a multiplier that we use to calculate the probability of the asteroid being large or the velocity of the asteroid and then we just instantiate that Factory and suddenly we have a level four that we know is harder than level two, level three, but it's less difficult than level five and I think, again, you can easily see how we could have the Asteroid Factory and we can have the Ignition Factory and other Factories and then we keep moving in that direction, so we're a kind of parameter. increasing all the parts of the system, which again moves the creation logic outside 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 need to worry about creation at all, it's just passed in some classes that are factories, some classes that are responsible for creation and just calls the appropriate method in these creation. classes that we previously called create animal or create product, okay, that's it.
Thank you so much for looking if you have any questions or comments or feel like I've misrepresented you or want to help other people try to understand what their pattern is. actually about or when it is useful, write anything in the comment and if you are new to pattern design I recommend you get this book, it's in the description and of course remember to subscribe so you don't miss the next one. pattern of this book and finally thanks again for watching. See you at the next one.

If you have any copyright issue, please Contact