我面对以下代码:
public class BaseGroup {
private Group1 group1;
private Group2 group2;
private Group3 group3;
public void setGroup (IGroup group) {
if(group instanceof Group1) {
setGroup1((Group1) group);
} else if(group instanceof Group2) {
setGroup2((Group2) group);
} else {
setGroup3((Group3) group);
}
}
public Group1 getGroup1() {
return group1;
}
public void setGroup1(Group1 group1) {
this.group1 = group1;
}
public Group2 getGroup2() {
return group2;
}
public void setGroup2(Group2 group1) {
this.group2 = group2;
}
public Group3 getGroup3() {
return group3;
}
public void setGroup3(Group3 group1) {
this.group3 = group3;
}
}
BaseGroup类以这种方式使用。
BaseGroup baseGroup = New BaseGroup();
basegroup.setGroup(group);
我的问题是关于这个“instanceof”的链调用相应的setter来组装BaseGroup对象。有什么更好的方法来做到这一点?
答案 0 :(得分:5)
您可以添加方法
interface IGroup {
public void addToGroup(BaseGroup bg);
}
class Group1 implements IGroup {
public void addToGroup(BaseGroup bg) { bg.setGroup1(this); }
}
// etc for Group2 and 3.
IGroup group;
BaseGroup bg;
group.addToGroup(bg);
答案 1 :(得分:1)
取决于您如何使用group1
,'group2','group3'。类似的东西可以起作用:
class BaseGroup {
private final List<Group> groups = new ArrayList<Group>();
public void addGroup(Group group) {
groups.add(group);
}
}
答案 2 :(得分:1)
多态性(特别是方法重载)实际上可以在这里工作。
public void setGroup(Group1 group) {
this.group1 = group;
}
public void setGroup(Group2 group) {
this.group2 = group;
}
public void setGroup(Group3 group) {
this.group3 = group;
}
Java会自动选择合适的方法。
答案 3 :(得分:0)
另一种选择是使用Reflection。
答案 4 :(得分:0)
public class BaseGroup {
private Map<Class<IGroup>, IGroup> groupsFactoryByClass;
public void setGroup (IGroup group) {
IGroup oldGroup = groupsFactoryByClass.put(group.getClass());
if (oldGroup != null)
throw new IllegalArgumentException("Group with class " + group.getClass().getName() + " already set");
}
public <T implements IGroup> getGroup(Class<T> klazz) {
return groupsFactoryByClass.get(klazz);
}
}
答案 5 :(得分:0)
interface Group{}
class Group1 implements Group{}
class Group2 implements Group{}
class Group3 implements Group{}
public class BaseGroup {
private Map<Class<Group>, <Group>> groups = new HashMap<Class<Group>, <Group>>();
public void setGroup (Group group) {
groups.put(group.getClass(), group);
}
}
答案 6 :(得分:-1)
避免实例的最好的事情是访客模式请使用那个。