OnJava8-Examples/patterns/ShapeFactory2.java

74 lines
1.8 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: patterns/ShapeFactory2.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-05-05 11:20:13 -07:00
// Polymorphic factory methods.
import java.util.*;
2015-05-27 23:30:19 -07:00
import java.util.function.*;
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);
}
}
interface Shape {
void draw();
void erase();
}
abstract class ShapeFactory {
2015-05-27 23:30:19 -07:00
static Map<String, Supplier<Shape>> factories =
2015-05-06 15:14:33 -07:00
new HashMap<>();
static Shape createShape(String id)
2015-05-05 11:20:13 -07:00
throws BadShapeCreation {
if(!factories.containsKey(id)) {
try {
Class.forName(id); // Load dynamically
} catch(ClassNotFoundException e) {
throw new BadShapeCreation(id);
}
// See if it was put in:
if(!factories.containsKey(id))
throw new BadShapeCreation(id);
}
2015-05-27 23:30:19 -07:00
return factories.get(id).get();
2015-05-05 11:20:13 -07:00
}
}
class Circle implements Shape {
private Circle() {}
2015-05-18 23:05:20 -07:00
public void draw() { print("Circle.draw"); }
public void erase() { print("Circle.erase"); }
2015-05-05 11:20:13 -07:00
static {
2015-05-27 23:30:19 -07:00
ShapeFactory.factories.put("Circle", Circle::new);
2015-05-05 11:20:13 -07:00
}
}
class Square implements Shape {
2015-05-06 15:14:33 -07:00
private Square() {}
2015-05-18 23:05:20 -07:00
public void draw() { print("Square.draw"); }
public void erase() { print("Square.erase"); }
2015-05-05 11:20:13 -07:00
static {
2015-05-27 23:30:19 -07:00
ShapeFactory.factories.put("Square", Square::new);
2015-05-05 11:20:13 -07:00
}
}
public class ShapeFactory2 {
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
ArrayList<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) {
shapes.add(
ShapeFactory.createShape(shlist1));
2015-05-05 14:05:39 -07:00
}
2015-05-05 11:20:13 -07:00
} catch(BadShapeCreation e) {
e.printStackTrace();
return;
}
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
} ///:~