//: c17:ShapeFactory1.java // From Thinking in Java, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 1999 // Copyright notice in Copyright.txt // A simple static factory method import java.util.*; class BadShapeCreation extends Exception { BadShapeCreation(String msg) { super(msg); } } abstract class Shape { public abstract void draw(); public abstract void erase(); static Shape factory(String type) throws BadShapeCreation { if(type == "Circle") return new Circle(); if(type == "Square") return new Square(); throw new BadShapeCreation(type); } } class Circle extends Shape { Circle() {} // Friendly constructor public void draw() { System.out.println("Circle.draw"); } public void erase() { System.out.println("Circle.erase"); } } class Square extends Shape { Square() {} // Friendly constructor public void draw() { System.out.println("Square.draw"); } public void erase() { System.out.println("Square.erase"); } } public class ShapeFactory1 { public static void main(String args[]) { String shlist[] = { "Circle", "Square", "Square", "Circle", "Circle", "Square" }; ArrayList shapes = new ArrayList(); try { for(int i = 0; i < shlist.length; i++) shapes.add(Shape.factory(shlist[i])); } catch(BadShapeCreation e) { e.printStackTrace(); return; } Iterator i = shapes.iterator(); while(i.hasNext()) { Shape s = (Shape)i.next(); s.draw(); s.erase(); } } } ///:~