| 8 | import patterns.shapes.*; |
| 9 | |
| 10 | public 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: |
| 37 | loading Circle |
| 38 | Circle[0] draw |
nothing calls this directly
no outgoing calls
no test coverage detected