import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
abstract class Shape {
public abstract void draw();
public abstract void erase();
public static Shape factory(String type) {
if (type.equals("Circle"))
return new Circle();
if (type.equals("Square"))
return new Square();
throw new RuntimeException("Bad shape creation: " + type);
}
}
class Circle extends Shape {
Circle() {
} // Package-access constructor
public void draw() {
System.out.println("Circle.draw");
}
public void erase() {
System.out.println("Circle.erase");
}
}
class Square extends Shape {
Square() {
} // Package-access constructor
public void draw() {
System.out.println("Square.draw");
}
public void erase() {
System.out.println("Square.erase");
}
}
public class ShapeFactory {
public static void main(String args[]) {
List<Shape> shapes = new ArrayList<Shape>();
Iterator it = Arrays.asList(
new String[] { "Circle", "Square", "Square", "Circle", "Circle", "Square" }).iterator();
while (it.hasNext())
shapes.add(Shape.factory((String) it.next()));
it = shapes.iterator();
while (it.hasNext()) {
Shape s = (Shape) it.next();
s.draw();
s.erase();
}
}
}
|