Factory manufactures objects
In this pattern, there is a factory and other objects. The factory provides you with the object that you require.
Note: If the factory contains sub-factories, then that is known as an abstract design pattern.
Example: There is a shape factory that gives all the geometrical shapes. The important thing to note is all the shapes implement an interface called Shape.
public class ShapeFactory {
Shape getShape(String input){
input = input.toLowerCase();
switch (input) {
case "circle":
return new Circle();
case "rectangle":
return new Rectangle();
default:
return null;
}
}
}
public interface Shape {
public void draw();
}
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Draw the circle");
}
}
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("Draw the circle");
}
}
Usage:
public class MainClass {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape circle = factory.getShape("Circle");
circle.draw();
}
}
Conclusion: A factory should manufacture products that belong to one family.