工場モード!@——@

8535 ワード

 1 package zzuli.acmen.my.factory;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 public class Factory {
7
8 Map<String,Object> map = new HashMap<String,Object>();
9
10 public void setObject(String str){
11
12 //
13 try {
14 /*
15 * 。 Object
16 */
17 Class c = Class.forName(str);
18 Object o = c.newInstance();
19 map.put(str, o);
20 } catch (ClassNotFoundException e) {
21 // TODO Auto-generated catch block
22 e.printStackTrace();
23 } catch (InstantiationException e) {
24 // TODO Auto-generated catch block
25 e.printStackTrace();
26 } catch (IllegalAccessException e) {
27 // TODO Auto-generated catch block
28 e.printStackTrace();
29 }
30
31
32 }
33
34 public Object getObject(String str){
35
36 Object o = map.get(str);
37
38 return o;
39
40 }
41 }
42
43 interface Person{
44
45 public void say(String str);
46
47 }
48
49 class One implements Person{
50
51 public void say(String str) {
52 System.out.println(" "+str);
53
54 }
55
56 }
57
58 class Two implements Person{
59
60 public void say(String str) {
61 System.out.println(" "+str);
62
63 }
64
65 }
 1 package zzuli.acmen.my.factory;
2
3 public class Main {
4
5 /**
6 * @param args
7 */
8 public static void main(String[] args) {
9
10 Factory f = new Factory();
11 /*
12 * ;
13 */
14 f.setObject("zzuli.acmen.my.factory.One");
15 f.setObject("zzuli.acmen.my.factory.Two");
16
17 /*
18 * Object ,
19 */
20 Person p = (Person)f.getObject("zzuli.acmen.my.factory.One");
21 p.say(" ");
22 Person pp = (Person)f.getObject("zzuli.acmen.my.factory.Two");
23 pp.say(" ");
24 Person p1 = (Person)f.getObject("zzuli.acmen.my.factory.One");
25 p1.say(" ");
26
27 }
28
29 }

ファクトリモードの私見では、ファクトリモードはアセンブリでオブジェクトの生成を呼び出した場所から解放するので、上のコードがあると思います!