gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:10:31 26 4
gpt4 key购买 nike

我创建了一个 Settings自动检索或打印关联 JTextField 上的设置值的类。我的绑定(bind)函数如下所示:

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

但是,我想使用更多类型的 JComponent 。我已经创建了更抽象的输入表示 - 接口(interface) 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();
}

现在看来我必须使用 long 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 是否有有效的实现.

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

最佳答案

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

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

register() 调用将如下所示:

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

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

inputRegistry.get(component.getClass());

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

关于java - 工程 OOP 模型,您可以在其中注册类类型的处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28797837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com