OnJava8-Examples/patterns/factory/ShapeFactory1.java

64 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.*;
2015-05-18 23:05:20 -07:00
import static net.mindview.util.Print.*;
2015-05-05 11:20:13 -07:00
class BadShapeCreation extends Exception {
BadShapeCreation(String msg) {
super(msg);
}
}
abstract class Shape {
public abstract void draw();
public abstract void erase();
2015-05-06 15:14:33 -07:00
static Shape factory(String type)
2015-05-05 11:20:13 -07:00
throws BadShapeCreation {
2015-05-18 23:05:20 -07:00
switch(type) {
case "Circle": return new Circle();
case "Square": return new Square();
default:
throw new BadShapeCreation(type);
}
2015-05-05 11:20:13 -07:00
}
}
class Circle extends Shape {
Circle() {} // Friendly constructor
@Override
2015-05-18 23:05:20 -07:00
public void draw() { print("Circle.draw"); }
2015-05-05 11:20:13 -07:00
@Override
2015-05-18 23:05:20 -07:00
public void erase() { print("Circle.erase"); }
2015-05-05 11:20:13 -07:00
}
class Square extends Shape {
Square() {} // Friendly constructor
@Override
2015-05-18 23:05:20 -07:00
public void draw() { print("Square.draw"); }
2015-05-05 11:20:13 -07:00
@Override
2015-05-18 23:05:20 -07:00
public void erase() { print("Square.erase"); }
2015-05-05 11:20:13 -07:00
}
public class ShapeFactory1 {
public static void main(String args[]) {
2015-05-06 15:14:33 -07:00
String shlist[] = { "Circle", "Square",
2015-05-05 11:20:13 -07:00
"Square", "Circle", "Circle", "Square" };
2015-05-06 15:14:33 -07:00
List<Shape> shapes = new ArrayList<>();
2015-05-05 11:20:13 -07:00
try {
2015-05-18 23:05:20 -07:00
for(String shlist1 : shlist) {
2015-05-05 14:05:39 -07:00
shapes.add(Shape.factory(shlist1));
}
2015-05-05 11:20:13 -07:00
} catch(BadShapeCreation e) {
e.printStackTrace();
return;
}
2015-05-06 15:14:33 -07:00
Iterator<Shape> i = shapes.iterator();
2015-05-05 11:20:13 -07:00
while(i.hasNext()) {
2015-05-06 15:14:33 -07:00
Shape s = i.next();
2015-05-05 11:20:13 -07:00
s.draw();
s.erase();
}
2015-05-06 15:14:33 -07:00
}
2015-05-05 11:20:13 -07:00
} ///:~