Factory Design Patterns
Factory Design Patterns And its Example
Intent:
Create objects without exposing the instantiation logic to the clients.
Applicability:Intent:
Create objects without exposing the instantiation logic to the clients.
- Client uses the Factory to create the product and then use it through common interface
- Factory instantiates the concrete product
- To control/manage the number of instances
- To conditionally instantiate objects
- To hide the concrete class details from the client by using a common interface for the newly created objects
Example applications:
- A drawing application need to create multiple types of shapes
- Java API examples:
– java.util.Collections
– javax.sql.DataSource
– java.sql.DriverManager
Implementation Issues:
Parameterized factories :
Avoid if/else blocks as it violates OCP.
Use reflection API to create respective concrete classes.
Structure
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.imageio.ImageReader;
public class ImageReaderFactory
{
private static final String GIF = "gif";
private static final String JPEG = "jpg";
private static Properties prop = null;
public static ImageReader getImageReader(InputStream is)
{
ImageReader reader = null;
if (prop == null) {
prop = new Properties();
try {
prop.load(new FileInputStream("D:\\test.prop"));
} catch(Exception ex) {ex.printStackTrace();}
}
String imageType = determineImageType(is);
String className = prop.getProperty(imageType);
if (className != null) {
try {
reader = (ImageReader)Class.forName(className).newInstance();
} catch (Exception ex) {ex.printStackTrace();}
}
return reader;
}
private static String determineImageType(InputStream is) {
return JPEG;
}
public static void main(String[] args) {
ImageReader reader = ImageReaderFactory.getImageReader(null);
System.out.println(reader);
}
}
package dp.factory;
public class JpegReader implements ImageReader
{
public DecodedImage getDecodedImage()
{
DecodedImage decodedImage = null;
// ...
return decodedImage;
}
}
package dp.factory;
public interface ImageReader
{
public DecodedImage getDecodedImage();
}
package dp.factory;
public class GifReader implements ImageReader
{
public DecodedImage getDecodedImage()
{
DecodedImage decodedImage = null;
// ...
return decodedImage;
}
}
package dp.factory;
public class DecodedImage {
}
