工程OOP模型,您可以在其中注册类类型的处理程序

时间:2015-03-01 19:10:54

标签: java oop

我创建了一个Settings类,可以自动检索或打印关联JTextField的设置值。我的绑定功能如下所示:

public void bindToInput(final String setting_name, final JTextField input, final SettingsInputVerifier<Object> verif);

但是,我想使用更多类型的JComponent。我已经创建了更抽象的输入表示 - 接口Input

public interface Input {
  /** Retrieve the field associated with this abstract input.
   * @return JComponent field. Use `instanceof` to check for type.
   */
  public JComponent getField();
  /**
   * Will put the best possible representation of the value in the input.
   * @param value to appear in the input
   */
  public void setValue(Object value);
  /** Parse input field value and turn it into object.
   * @return Object representing parsed value of the input field
   */
  public Object getValue();
  /**
   * Check if the value in JComponent is valid using the associated verifier.
   * @return true if the value is valid and can be turned into type <T>
   */
  public boolean validate();
  /**
   * Retrieve the internal verifier.
   * @return SettingsInputVerifier
   */
  public SettingsInputVerifier<Object> getVerifier();
  /**
   * Change the internal verifier.
   * @param ver verifier to replace the original input verifier. Pass null to skip value verification.
   */
  public void setVerifier(SettingsInputVerifier<Object> ver);
  /**
   * Add the verifier
   */
  public void bind();
  /**
   * Remove the verifier from input, do not call onchange event any more
   */
  public void unbind();
}

现在看来,我必须使用长else if个链来为给定的Input使用正确的JComponent实现。像这样:

//InputJTextField, InpuJToggleButton are, WLOG, some classes inplementing Input
public static Input fromJComponent(JComponent something) {
     if(something instanceof JTextField)
       return new InputJTextField(something);
     else if(something instanceof JToggleButton)
       return new InpuJToggleButton(something);
     if(... and so on...
        ...
     else
        throw new InvalidArgumentException("This input type is not supported.");
}

而不是这个else if链,我希望有一个选项可以在每个实现Input的类中注册:

class InputJToggleButton implements Input {
    //Register the association with this class and the input type it represents
    private final boolean registered = Input.register(InputJToggleButton, JToggleButton);
}

然后,fromJComponent方法会查找一些HashMap<Type, Type>并查找给定JComponent是否存在有效的实现。

这种灵活性是否可行?或者我是否必须手动添加else if链中的每个实现?

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。您可以将组件类中的映射注册到输入类:

Map<Class<? extends JComponent>, Class<? extends Input>> inputRegistry;

register()调用看起来像这样:

Input.register(JToggleButton.class, InputJToggleButton.class);

然后你可以从Map获取Input类:

inputRegistry.get(component.getClass());

然后使用反射(Class.newInstance())创建一个Input实例。