2015-09-07 11:44:36 -06:00
|
|
|
// patterns/ShapeFactory2.java
|
2020-10-07 13:35:40 -06:00
|
|
|
// (c)2020 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
2017-01-08 22:55:49 -08:00
|
|
|
import java.lang.reflect.*;
|
2015-11-03 12:00:44 -08:00
|
|
|
import java.util.stream.*;
|
2017-01-08 22:55:49 -08:00
|
|
|
import patterns.shapes.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2017-01-09 14:26:12 -08:00
|
|
|
public class ShapeFactory2 implements FactoryMethod {
|
|
|
|
Map<String, Constructor> factories =
|
2015-06-15 17:47:35 -07:00
|
|
|
new HashMap<>();
|
2017-01-08 22:55:49 -08:00
|
|
|
static Constructor load(String id) {
|
|
|
|
System.out.println("loading " + id);
|
|
|
|
try {
|
|
|
|
return Class.forName("patterns.shapes." + id)
|
|
|
|
.getConstructor();
|
2017-01-09 14:26:12 -08:00
|
|
|
} catch(ClassNotFoundException |
|
|
|
|
NoSuchMethodException e) {
|
2017-01-08 22:55:49 -08:00
|
|
|
throw new BadShapeCreation(id);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-11-03 12:00:44 -08:00
|
|
|
}
|
2017-01-09 14:26:12 -08:00
|
|
|
public Shape create(String id) {
|
2017-01-08 22:55:49 -08:00
|
|
|
try {
|
|
|
|
return (Shape)factories
|
2017-01-09 14:26:12 -08:00
|
|
|
.computeIfAbsent(id, ShapeFactory2::load)
|
2017-01-08 22:55:49 -08:00
|
|
|
.newInstance();
|
2020-10-07 17:06:42 -06:00
|
|
|
} catch(Exception e) {
|
2017-01-08 22:55:49 -08:00
|
|
|
throw new BadShapeCreation(id);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void main(String[] args) {
|
2017-01-09 14:26:12 -08:00
|
|
|
FactoryTest.test(new ShapeFactory2());
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2017-01-08 22:55:49 -08:00
|
|
|
loading Circle
|
|
|
|
Circle[0] draw
|
|
|
|
Circle[0] erase
|
|
|
|
loading Square
|
|
|
|
Square[1] draw
|
|
|
|
Square[1] erase
|
|
|
|
loading Triangle
|
|
|
|
Triangle[2] draw
|
|
|
|
Triangle[2] erase
|
|
|
|
Square[3] draw
|
|
|
|
Square[3] erase
|
|
|
|
Circle[4] draw
|
|
|
|
Circle[4] erase
|
|
|
|
Circle[5] draw
|
|
|
|
Circle[5] erase
|
|
|
|
Triangle[6] draw
|
|
|
|
Triangle[6] erase
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|