Content deleted Content added
add missing void |
m Reformatted the code to agree with Java Coding Conventions |
||
Line 6:
public class ImageReader {
private int fileType;
public ImageReader( InputStream in ) {
// Figure out what type of file this input stream represents
// (eg gif, jpeg, png, tif, etc )
this.fileType = fileType;
decodeFile();
}
switch( fileType ) {
case ImageReader.GIF:
// do gif decoding (many lines)
break;
case ImageReader.JPEG:
// do jpeg decoding (many lines)
break;
case ImageReader.PNG:
// do png decoding (many lines)
break;
// etc...
}
}
}
Line 46 ⟶ 41:
Another solution that seems possible is to have a separate [[Object (computer science)|object]] for each of these file types:
public Interface ImageReader {
public ImageReader( InputStream in );
public getDecodedImage();
}
public class GifReader implements ImageReader {
public GifReader( InputStream in ) {
// check that it's a gif, throw exception if it's not, then if it is
// decode it.
}
public getDecodedImage() {
return DecodedImage;
}
}
public class JpegReader implements ImageReader {
}
// Then you would use them as:
public class MyProg {
if( endsInDotGif( filename )) {
out = (ImageReader)new GifReader( fileInputStream );
}
out = (ImageReader)new JpegReader( fileInputStream );
}
}
Line 96 ⟶ 87:
So what's the solution ? Simply to take the best of both worlds, by using the Factory pattern (which you should already have an idea of by now). The [[Factory]] is a class that returns another class depending on the [[context]]. So in this situation, keeping the separate [[class design]] as in the last example:
public class ImageReaderFactory {
public static ImageReader getImageReader( InputStream is ) {
int ImageType = figureOutImageType( is );
case ImageReaderFactory.GIF:
GifReader r = new GifReader( is );
return( (ImageReader)r );
break;
case ImageReaderFactory.JPEG:
JpegReader r = new JpegReader( is );
return( (ImageReader)r );
break;
// etc.
}
}
|