I believe the factory method design pattern is appropriate for what I'm trying to do, but I'm not sure how much responsibility (knowledge of subclasses it creates) to give it. The example of using the factory method pattern at Wikipedia describes the situation I'm in almost exactly:
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.
}
}
}
My question is, what does the figureOutImageType
function look like? In this specific example, I would assume that it checks a file header in the InputStream
to determine which image format the data is in. I would like to know if the ImageReaderFactory
itself knows how to parse file headers and determine if the file type is GIF, JPEG, etc, or if it calls a function inside each Reader
class that lets it know what type of image it is. Something like this, maybe:
int figureOutImageType(InputStream is)
{
if(GifReader.isGIF(is))
return ImageReaderFactory.GIF;
else if(JpegReader.isJPEG(is))
return ImageReaderFactory.JPEG;
// etc.
}
It seems like having the factory know how to parse images breaks encapsulation, and letting the subclasses decide which one should be created is part of the factory method design pattern. Yet, it also seems like the figureOutImageType
function is just adding some redundant code, because why not just have each subclass perform its check on the InputStream
in the getImageReader
function and skip the switch case?
I haven't had any experience using factories before, and I was hoping to get some insight from some people who have used them in the past on the best way to handle this problem. Is it okay to have the factory know about the inner workings of its subclasses, or should they be responsible for letting the factory know which to create, and how do you organize it all?
Thanks!