“实例”链组装一个物体
我面临以下代码:
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);
我的问题是关于调用相应设置器来组装 BaseGroup 对象的“instanceof”链。执行此操作的更好方法是什么?
I'm facing the following code:
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;
}
}
And the BaseGroup class is used in this way.
BaseGroup baseGroup = New BaseGroup();
basegroup.setGroup(group);
My question is about this chain of "instanceof's" calling the respective setters to assemble the BaseGroup object. What is the better approach to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以添加一个方法
You can add a method to
取决于您如何使用
group1
、'group2'、'group3'。类似的东西可以工作:Depends on how you use
group1
, 'group2', 'group3'. Something like that could work:多态性(特别是方法重载)实际上可能在这里起作用。
Java会自动选择合适的方法。
Polymorphism (specifically method overloading) may actually work here.
Java will automatically select the appropriate method.
另一种选择是使用反射。
Another alternative is using Reflection.
最好避免的情况是访问者模式,请使用该模式。
The best thing to avoid instance of is visitor pattern please use that one.