Factory method pattern: Difference between revisions

Content deleted Content added
Gnyus (talk | contribs)
m changed 'bung' to 'bundle' and removed a space before a question mark
Line 4:
 
The Factory pattern is useful to solve a common problem: Very often you'll have to construct an [[Object (computer science)|object]], based on some [[input]], and the [[function (programming)|function]]s inside the object will depend upon the input. A good example would be a [[class (computer science)|class]] to read [[image file]]s and make [[thumbnail]]s out of them. You could, of course, bundle them all into one class and have it decide which bit of code to run on its own:
 
 
public class ImageReader {
Line 50 ⟶ 49:
// decode it.
}
 
public DecodedImage getDecodedImage() {
return decodedImage;
}
}
 
public class JpegReader implements ImageReader {
//...
Line 62 ⟶ 61:
// Then you would use them as:
public class MyProg {
 
public static void main( String[] args ) {
 
String filename = args[0];
ImageReader out;
Line 71 ⟶ 70:
out = (ImageReader)new GifReader( fileInputStream );
}
 
if( endsInDotJpeg( filename )) {
out = (ImageReader)new JpegReader( fileInputStream );
}
 
printOut( out.getDecodedImage );
}
Line 89 ⟶ 88:
public static ImageReader getImageReader( InputStream is ) {
int ImageType = figureOutImageType( is );
 
switch( ImageType ) {
case ImageReaderFactory.GIF: