Design Patterns

Table of Contents

Creational
Abstract Factory
Builder
Factory Method
Prototype
Singleton

Structural
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy

Behavioral
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor

Java EE
Model View Controller
Business Delegate
Composite Entity
Data Access Object
Front Controller
Intercepting Filter
Service Locator
Transfer Object

UML & OOD
Unified Modeling Language
SOLID

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

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();
    }
}