Let's now look at the first design pattern that we
will discuss, the factory method pattern. And I'm going to start
by discussing the intent of the pattern and its applicability.
As far as the intent is concerned, the factory method pattern
allows for creating objects without specifying their class, by invoking
what we call a factory method. And what that is, is
a method whose main goal is to create class instances.
So when is this pattern useful? So when is it applicable?
For example, it is applicable in cases in which a class
cannot anticipate the type of object it must create. That is,
the type of an object is not known at compile time,
is not known until the code runs. A typical example of
this, are frameworks. So if you ever used a framework, you
will know that, normally, frameworks only know about interfaces and abstract
classes. So the exact type of the objects of these classes
is only known at runtime. The second case in which the factory
method pattern is applicable, is when a class wants its
subclasses to specify the type of objects it creates. And we'll
see an example of this in a minute. Finally, factory
method patterns are applicable when a class needs control over the
creation of its objects. And in this case, one possible
example is when there is a limit on the number of
objects that can be created. Special example, it's a singleton. If
you're familiar with a singleton, a singleton is a class for
which only one instance can be created. The factory method pattern
is perfect in these cases, because it allows to control how many
objects get created. So in this case, it would allow the creation
only of a single object. And from the second time that it
is invoked, it will just return the object that was previously
created. Now let's go ahead and see how this pattern actually works,
and let's do that by discussing the structure and the participants for
the pattern. The structure that is represented here, using the UML notation,
includes three classes, the Creator, the ConcreteCreator,
and the Product. The Creator provides the
interface for the factory method. So this
here, is the interface for the factory method
that, when invoked, returns an object of
type Product. The ConcreteCreator provides the actual
method for creating the Product. So this
method is a concrete implementation of this interface.
Finally, the Product is the object created by the factory method. So
summarizing, we have the interface for
the factory method, the actual implementation of
the summary method, and the object that is created by the factory method,
when it is invoked. So let's look at an example of this pattern.