OnJava8-Examples/patterns/factory/ShapeFactory1.java

68 lines
1.5 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: patterns/factory/ShapeFactory1.java
// A simple static factory method.
package patterns.factory;
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 {
2015-05-06 12:09:38 -07:00
if("Circle".equals(type)) return new Circle();
if("Square".equals(type)) return new Square();
2015-05-05 11:20:13 -07:00
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[]) {
String shlist[] = { "Circle", "Square",
"Square", "Circle", "Circle", "Square" };
ArrayList shapes = new ArrayList();
try {
2015-05-05 14:05:39 -07:00
for (String shlist1 : shlist) {
shapes.add(Shape.factory(shlist1));
}
2015-05-05 11:20:13 -07:00
} catch(BadShapeCreation e) {
e.printStackTrace();
return;
}
Iterator i = shapes.iterator();
while(i.hasNext()) {
Shape s = (Shape)i.next();
s.draw();
s.erase();
}
}
} ///:~