【发布时间】:2020-07-06 08:37:25
【问题描述】:
我有一个父接口。
public interface Parent{...}
还有两个实现这个接口的类。
public class ChildA implements Parent {...}
public class ChildB implements Parent {...}
现在我想根据传递的参数创建一个孩子的对象。像这样的,
Parent instance1 = Parent.getChild("Key1");
目前,我正在通过使用 hashmaps 来实现这一点。
static Map<String,Class<?>> map = new HashMap<String,Class<?>>();
static void init() throws ClassNotFoundException {
map.put("Key1",Class.forName("ChildA"));
map.put("Key2",Class.forName("ChildB"));
}
static Parent getChild(String key) throws InstantiationException, IllegalAccessException {
return (Parent) map.get(key).newInstance();
}
但是这里的问题是每次我实现一个新的孩子时,我都必须将它添加到 Parent init 方法中。那么有没有更清洁的方法来做到这一点?比如给孩子本身添加钥匙的信息,
public class ChildA implements Parent {
private String key = "Key1";
...
因此,当我从父类调用 getChild 时,它指的是相应的 Child。
基本上,我要求一种基于传递的参数动态引用父级子级的方法。
【问题讨论】:
-
我想你说的是策略模式,在这里查看journaldev.com/1754/…
-
我认为你可以使用类名作为键,当你放入map时你可以使用getClass().getSimpleName(),即你应该以某种方式自动化关键值,我的只是一个想法。
-
试试这个,添加你的键名约束stackoverflow.com/questions/3123095/…