MCPcopy Index your code
hub / github.com/BruceEckel/OnJava8-Examples / ShapeFactory2

Class ShapeFactory2

patterns/ShapeFactory2.java:10–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8import patterns.shapes.*;
9
10public class ShapeFactory2 implements FactoryMethod {
11 private Map<String, Constructor> factories =
12 new HashMap<>();
13 private static Constructor load(String id) {
14 System.out.println("loading " + id);
15 try {
16 return Class.forName("patterns.shapes." + id)
17 .getConstructor();
18 } catch(ClassNotFoundException |
19 NoSuchMethodException e) {
20 throw new BadShapeCreation(id);
21 }
22 }
23 @Override public Shape create(String id) {
24 try {
25 return (Shape)factories
26 .computeIfAbsent(id, ShapeFactory2::load)
27 .newInstance();
28 } catch(Exception e) {
29 throw new BadShapeCreation(id);
30 }
31 }
32 public static void main(String[] args) {
33 FactoryTest.test(new ShapeFactory2());
34 }
35}
36/* Output:
37loading Circle
38Circle[0] draw

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected