zoukankan      html  css  js  c++  java
  • 工厂模式

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

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

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

    配置文件格式:

    代码示例:

     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     }
  • 相关阅读:
    Java中-classpath和路径的使用
    总是分不清
    Maven Web项目部署到Tomcat下问题
    一、数据设计规范
    一、入职学习
    一、服务器控件
    WebApiThrottle限流框架
    一、接口的规则
    一、免费API调用
    十、锁
  • 原文地址:https://www.cnblogs.com/nicker/p/6274888.html
Copyright © 2011-2022 走看看