// patterns/factory/ShapeFactory1.java // ©2016 MindView LLC: see Copyright.txt // A simple static factory method. package patterns.factory; import java.util.*; import java.util.stream.*; class BadShapeCreation extends RuntimeException { BadShapeCreation(String msg) { super(msg); } } abstract class Shape { public abstract void draw(); public abstract void erase(); static Shape factory(String type) throws BadShapeCreation { switch(type) { case "Circle": return new Circle(); case "Square": return new Square(); default: throw new BadShapeCreation(type); } } } class Circle extends Shape { Circle() {} // Friendly constructor @Override public void draw() { System.out.println("Circle.draw"); } @Override public void erase() { System.out.println("Circle.erase"); } } class Square extends Shape { Square() {} // Friendly constructor @Override public void draw() { System.out.println("Square.draw"); } @Override public void erase() { System.out.println("Square.erase"); } } public class ShapeFactory1 { public static void main(String args[]) { List shapes = Stream.of( "Circle", "Square", "Square", "Circle", "Circle", "Square") .map(Shape::factory) .collect(Collectors.toList()); shapes.forEach(Shape::draw); shapes.forEach(Shape::erase); } } /* Output: Circle.draw Square.draw Square.draw Circle.draw Circle.draw Square.draw Circle.erase Square.erase Square.erase Circle.erase Circle.erase Square.erase */