In a nutshell, factory methods encapsulate the creation of objects. They create complex objects for you so you don't have to bother.
In your example:
public class ImageReaderFactory {
public static ImageReader getImageReader(InputStream is) {
int imageType = figureOutImageType( is );
switch( imageType ) {
case ImageReaderFactory.GIF:
return new GifReader( is );
case ImageReaderFactory.JPEG:
return new JpegReader( is );
// etc.
}
}
}
Who's creating the ImageReader
objects (calling their constructors) and returning them? Neither figureOutImageType()
or the method of the GifReader
class (or the others JpegReader
or possibly PngReader
, TiffReader
, etcReader
...).
Ultimately, getImageReader()
is creating them for you. This is the method you call asking "hey, create me a ImageReader
, please" and it does the rest.
So, at best, public static ImageReader getImageReader(InputStream is) {}
is the closest (see update below) to a factory method.
Update:
Bear in mind this design is not strictly a "Factory Method Pattern". This is presented as a variant of it.
The reason for this has been discussed in other answers, so allow me to just quote one here (slightly adapted):
(...) this snippet is not a proper implementation of the "Factory Method OO Design Pattern", since it does not satisfy "a class defer instantiation to subclasses." Though, personally I would freely refer to this solution as "factory method".
To make it real factory method pattern, you need to allow the method to be overridden by subclasses. I.e. factory class (ImageReaderFactory
) needs to be extensible (i.e. non-static
), and getImageReader
needs to be abstract
.