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