File tree Expand file tree Collapse file tree
src/designpattern/factory/abstraction Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package designpattern .factory .abstraction ;
2+
3+ import designpattern .factory .simple .Operation ;
4+
5+ /**
6+ * 客户端
7+ *
8+ * @author liu yuning
9+ *
10+ */
11+ public class Client {
12+ public static void main (String [] args ) throws InstantiationException ,
13+ IllegalAccessException {
14+ Operation operation = OperationFactory .createOperation ("/" );
15+
16+ operation .numberA = 7 ;
17+ operation .numberB = 8 ;
18+
19+ System .out .println (operation .result ());
20+ }
21+ }
Original file line number Diff line number Diff line change 1+ package designpattern .factory .abstraction ;
2+
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+
6+ import designpattern .factory .simple .Operation ;
7+ import designpattern .factory .simple .OperationAdd ;
8+ import designpattern .factory .simple .OperationDiv ;
9+ import designpattern .factory .simple .OperationMul ;
10+ import designpattern .factory .simple .OperationSub ;
11+
12+ /**
13+ * 利用反射改造简单工厂模式,去掉分支判断的逻辑
14+ *
15+ * @author liu yuning
16+ *
17+ */
18+ public class OperationFactory {
19+ private static Map <String , Class <?>> allOperationMaps = new HashMap <String , Class <?>>();
20+
21+ public static void fillMap () {
22+ allOperationMaps .put ("+" , OperationAdd .class );
23+ allOperationMaps .put ("-" , OperationSub .class );
24+ allOperationMaps .put ("*" , OperationMul .class );
25+ allOperationMaps .put ("/" , OperationDiv .class );
26+ }
27+
28+ public static Operation createOperation (String operator )
29+ throws InstantiationException , IllegalAccessException {
30+ Operation operation ;
31+
32+ fillMap ();
33+ Class <?> operationClass = allOperationMaps .get (operator );
34+
35+ if (operationClass == null ) {
36+ throw new RuntimeException ("unsupported operation" );
37+ }
38+
39+ operation = (Operation ) operationClass .newInstance ();
40+
41+ return operation ;
42+ }
43+
44+ }
You can’t perform that action at this time.
0 commit comments