zoukankan      html  css  js  c++  java
  • 001 ObjectFactory

    ObjectFactory: 对象工厂,在框架内容使用该对象进行对象的创建.
    public interface ObjectFactory {
      // 给对象工厂设置一些属性值
      void setProperties(Properties properties);
      // 使用类型字节码创建对象
      <T> T create(Class<T> type);
      // 使用构造函数创建对象
      <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs);
      // 判断一个类型是否是一个集合类型.
      <T> boolean isCollection(Class<T> type);
    
    }
    

    在框架内容,只有一个默认的实现类,一般情况下,我们也会使用这个实现类来完成功能.

    DefaultObjectFactory:

      @Override
      public void setProperties(Properties properties) {
        // no props for default
      }  

      我们看到默认的对象工厂是不支持属性配置的.

    我们看看到底是怎么创建对象的.

    private  <T> T instantiateClass(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
        try {
          Constructor<T> constructor;
          if (constructorArgTypes == null || constructorArgs == null) {
            constructor = type.getDeclaredConstructor();
            try {
              return constructor.newInstance();
            } catch (IllegalAccessException e) {
              if (Reflector.canControlMemberAccessible()) {
                constructor.setAccessible(true);
                return constructor.newInstance();
              } else {
                throw e;
              }
            }
          }
          constructor = type.getDeclaredConstructor(constructorArgTypes.toArray(new Class[constructorArgTypes.size()]));
          try {
            return constructor.newInstance(constructorArgs.toArray(new Object[constructorArgs.size()]));
          } catch (IllegalAccessException e) {
            if (Reflector.canControlMemberAccessible()) {
              constructor.setAccessible(true);
              return constructor.newInstance(constructorArgs.toArray(new Object[constructorArgs.size()]));
            } else {
              throw e;
            }
          }
        } catch (Exception e) {
          String argTypes = Optional.ofNullable(constructorArgTypes).orElseGet(Collections::emptyList)
              .stream().map(Class::getSimpleName).collect(Collectors.joining(","));
          String argValues = Optional.ofNullable(constructorArgs).orElseGet(Collections::emptyList)
              .stream().map(String::valueOf).collect(Collectors.joining(","));
          throw new ReflectionException("Error instantiating " + type + " with invalid types (" + argTypes + ") or values (" + argValues + "). Cause: " + e, e);
        }
      }
    

      上面的代码十分简单,首先判断创建的参数是否指明有构造函数参数,如果不存在的话,我们就使用默认的构造函数进行创建,否则我们使用指明的对象工厂来创建指定的对象.

  • 相关阅读:
    iOS深入学习(Block全面分析)
    iOS 多快好省的宏定义
    1.ARC和非ARC文件共存
    简单的实现UIpicker上面的取消确定按钮
    ios 简单的倒计时验证码数秒过程实现
    jquerymobile 基础教程
    得到UIView中某个非子视图在UIView中的位置
    状态栏问题
    html表格,列表
    html简单样式
  • 原文地址:https://www.cnblogs.com/trekxu/p/12835846.html
Copyright © 2011-2022 走看看