Factory method Design Pattern in Java

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Advantages of Factory Pattern

1.It can be used to unify the creation of objects sharing a commonality, e.g. in caching: CacheFactory -> Memcache, Filecache, … Working with each cache is similar, but setting up different caching strategies may differ vastly. When using the factory method you can switch between different caching strategies more easily, at best by just chaning one line of code factory(“Memcache”, options),without having to worry about the intricacies of the specific backend;
2.Improves loose Coupling

Also, disadvantage of Factory Pattern is loose coupling by means of additional objects results in decreased performance.

Below is an example of Factory Design Pattern.

public interface ImageReader {
    public DecodedImage 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 DecodedImage getDecodedImage() {
       return decodedImage;
    }
}

public class JpegReader implements ImageReader {
    public JpegReader( InputStream in) {
    }

    public DecodedImage getDecodedImage() {
      return decodedImage;
    }
}

public class PngReader implements ImageReader {
    public PngReader( InputStream in) {
    }

    public DecodedImage getDecodedImage() {
      return decodedImage;
    }
}

public class ImageFactory {

   //use getShape method to get object of type shape
   public static ImageReader getImageReader(String fileName){
      //open file and get type of file
      String file_type = ;
      if(file_type.equalsIgnoreCase("GIF")){
         return new GifReader();

      } else if(file_type.equalsIgnoreCase("JPEG")){
         return new JpegReader();

      } else if(file_type.equalsIgnoreCase("PNG")){
         return new PngReader();
      }

      return null;
   }
}

public class MyImageDemo{
   public static void main(String args[])
   {
       String image_file_name = "abc.gif";
       ImageReader ir = ImageFactory.getImageReader(image_file_name);
       DecodedImage di = ir.getDecodedImage();

       //DecodedImage object may be used to display image,etc...
   }
}