Dev_Nick

导航

工厂模式

工厂设计模式就是用于产生对象的。

该模式将创建对象的过程放在了一个静态方法中来实现.在实际编程中,如果需要大量的创建对象,该模式是比较理想的。

利用配置文件来动态产生对象

配置文件格式:

代码示例:

 1 //需求: 编写一个工厂方法根据配置文件返回对应的对象。
 2     public static Object getInstance() throws Exception{
 3         //读取配置文件
 4         BufferedReader bufferedReader = new BufferedReader(new FileReader("info.txt"));
 5         //读取第一行 : 读取类文件的信息
 6         String className = bufferedReader.readLine();
 7         //通过完整类名获取对应 的Class对象
 8         Class clazz = Class.forName(className);
 9         //获取到对应的构造方法
10         Constructor constructor = clazz.getDeclaredConstructor(null);
11         constructor.setAccessible(true);
12         Object o  = constructor.newInstance(null);
13         //给对象设置对应的属性值
14         String line = null;
15         while((line = bufferedReader.readLine())!=null){
16             String[] datas = line.split("=");
17             Field field =clazz.getDeclaredField(datas[0]);
18             //设置可以访问
19             field.setAccessible(true);
20             if(field.getType()==int.class){
21                 field.set(o, Integer.parseInt(datas[1]));
22             }else{
23                 field.set(o, datas[1]);
24             }
25         }
26         return o;
27         
28     }

 

posted on 2017-01-11 19:23  Dev_Nick  阅读(160)  评论(0编辑  收藏  举报