工厂模式

工厂设计模式是反射的典型应用。反射经常用于写一些通用的工具。

所以说,看工厂模式,放射应当是了然于胸了。

 1 import cn.itcast.reflect.Person;
 2 
 3 /*
 4 工厂设计模式就是用于产生对象 的。
 5 */
 6 class Car{}
 7 
 8 class BMW extends Car{}
 9 
10 class BSJ extends Car{}
11 
12 
13 
14 public class Demo1 {
15 
16     public static void main(String[] args) throws Exception {
17         Person p = (Person) getInstance();
18         System.out.println(p);
19     }
20     
21     //需求: 编写一个工厂方法根据配置文件返回对应的对象。
22     public static Object getInstance() throws Exception{
23         //读取配置文件
24         BufferedReader bufferedReader = new BufferedReader(new FileReader("info.txt"));
25         //读取第一行 : 读取类文件的信息
26         String className = bufferedReader.readLine();
27         //通过完整类名获取对应 的Class对象
28         Class clazz = Class.forName(className);
29         //获取到对应的构造方法
30         Constructor constructor = clazz.getDeclaredConstructor(null);
31         constructor.setAccessible(true);
32         Object o  = constructor.newInstance(null);
33         //给对象设置对应的属性值
34         String line = null;
35         while((line = bufferedReader.readLine())!=null){
36             String[] datas = line.split("=");
37             Field field =clazz.getDeclaredField(datas[0]);
38             //设置可以访问
39             field.setAccessible(true);
40             if(field.getType()==int.class){
41                 field.set(o, Integer.parseInt(datas[1]));
42             }else{
43                 field.set(o, datas[1]);
44             }
45         }
46         return o;
47     }
原文地址:https://www.cnblogs.com/OliverZhang/p/6027295.html