Factory Method
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
Factory Method in Java recognizable by creational methods returning an implementation of an abstract/interface type
java.util.Calendar#getInstance()
java.util.ResourceBundle#getBundle()
java.text.NumberFormat#getInstance()
java.nio.charset.Charset#forName()
java.net.URLStreamHandlerFactory#createURLStreamHandler(String)
(Returns singleton object per protocol)java.util.EnumSet#of()
javax.xml.bind.JAXBContext#createMarshaller()
and other similar methods
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class Shapeless implements Shape {
@Override
public void draw() {
System.out.println("Shapeless");
}
}
public enum ShapeFactory {
CIRCLE(Circle.class),
SQUARE(Square.class),
RECTANGLE(Rectangle.class);
private final Class<? extends Shape> clazz;
private ShapeFactory(Class<? extends Shape> clazz) {
this.clazz = clazz;
}
public Shape getShape() {
try {
return this.clazz.newInstance();
}
catch(Exception e) {
// log...
e.printStackTrace();
}
finally {
return new Shapeless(); // default or return null
}
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
Shape shape = ShapeFactory.CIRCLE.getShape();
shape.draw();
shape = ShapeFactory.RECTANGLE.getShape();
shape.draw();
shape = ShapeFactory.SQUARE.getShape();
shape.draw();
}
}