OnJava8-Examples/patterns/factory/ShapeFactory1.java

60 lines
1.4 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: patterns/factory/ShapeFactory1.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-05-05 11:20:13 -07:00
// 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) {
2015-06-03 11:41:10 -07:00
throw new RuntimeException(e);
2015-05-05 11:20:13 -07:00
}
2015-05-27 23:30:19 -07:00
shapes.forEach(Shape::draw);
shapes.forEach(Shape::erase);
2015-05-06 15:14:33 -07:00
}
2015-05-05 11:20:13 -07:00
} ///:~