Lecture thumbnail 0:03 / 2:22 All right.
We are now going to take a look at factories.
And this covers two design patterns at the same time.
This covers the factory method pattern as well as the abstract factory.
Now, the factory method is something that’s very common and the abstract factory is something that
is relatively rare, shall we say.
So what is the motivation behind using factories in the first place?
Well, it’s just like with the builder object creation logic sometimes becomes too convoluted and the
constructor is not really a great way to describe how to construct an object.
There are lots of limitations, like one limitation, for example, is that the name of the constructor
has to match the name of the containing type, so you cannot communicate additional information about
how the object is constructed or what the arguments are in the constructor name.
In addition, you have this limitation that because all of the constructors are named the same, you
cannot overload the constructor with the same sets of arguments.
You cannot have a constructor taking X and Y and another constructor taking rho and theta of the same
type.
That’s simply not allowed.
And generally what happens if you decide to stick with constructors is your objects turned into what
I call optional parameter hell.
So you end up making some of the constructor arguments optional and then you start getting confused
about the order in which all of these arguments have to appear and so on and so forth.
So it becomes really tedious.
So essentially what happens with the factories is you we look at object creation and by that we’re talking
about wholesale object creation and not piece wise creation like in the builder.
So in the case of a builder, you’re building up an object piece by piece in the factory or the typical
implementation of factories.
You are still creating an object in one invocation, but the act of creating an object is outsourced
from the actual object to something else.
And that can be a separate function, a separate static function, for example.
And that is the factory method that we looked at.
It can also exist in a separate class, and that is what is called a factory.
And in addition, in some of the really advanced sort of enterprise cases, you can have hierarchies
of factories and that implements the abstract factory pattern.
So the factory is quite simply a component whose sole responsibility is the wholesale creation of objects.
Stop Play Play Play Play Play Play Play Play Start Play information alert