The example I'm going to use consists of a class called
ImageReaderFactory which provides the factory method which is this one;
createImageReader. As you can see the method takes an InputStream
as input and returns an object of type ImageReader, and it's
static so that we can invoke it even if we
don't have an instance of the ImageReaderFactory. So what does the
method do? Well the method first invokes, getImageType, passing the
InputStream as a parameter and this method figures out the type
of the image that is stored in this Inputstream and it's
an integer. Then, based on the value of this integer, the
method does one of several things. If the image type is
a GIF, it will invoke the constructor for GifReader passing the
stream as a parameter. And what will happen is that the
GIF reader will read a GIF from the stream, create a
corresponding object and return it. So in this case, the ImageReader
object return will be the object representing a GIF as appropriate.
Similarly, if the image type is JPEG, then the method will
invoke the constructor for JPEG Reader and in this case, this constructor
will read from the stream a JPEG, create a corresponding object
and return it. And so on for different types of images. So
why is this a situation in which it is appropriate to
use the factory method pattern? One, because it corresponds exactly to the
cases that we saw before, of applicability. This is a case
in which we don't know the type of the object that we
need to create until we run the code, because it depends
on the value of the InputStream. It depends on the content
of the InputStream. So, until we read the InputStream, we cannot
figure out whether we need to create a GIF, a JPEG or
some other type of image. So in this case, we want to
do, we want to simply delegate to this classes the creation of
the object, once we know what type of object needs to
be created. So perfect example of application of a factory method pattern.