[英]How can I use composition of the classes if they have common fields in java?
如果它们具有共同的字段并且我希望它们相等,我该如何使用它们的组合?
例如,我有 3 个课程:
class SwimmingMonster
、 FlyingMonster
和SwimmAndFlyMonster
组成FlyingMonster
和SwimmingMonster
。 这两个类都有字段location
。 我希望它在SwimAndFly
class 中的对象objOfFly
和objOfSwim
中相同。
class SwimmingMonster{
private int[] location=new int[2];
{location[0]=0;
location[1]=0;}
void swim(int x,int y){
location[0]+=x;
location[1]+=y;}
}
class FlyingMonster{
private int[] location=new int[2];
{location[0]=0;
location[1]=0;}
void fly(int x,int y){
location[0]+=x;
location[1]+=y;}
}
class SwimAndFlyMonster{
private FlyingMonster objOfFly=new FlyingMonster();
private SwimmingMonster objOfSwim=new SwimmingMonster();
void fly(int x,int y){
objOfFly.fly(x,y);
}
void swim(int x,int y){
objOfSwim.swim(x,y);
}
}
但这里的问题是我希望objOfSwim
和objOfFly
中的字段location
相等。
那我该怎么做呢?
唯一的解决方案是为每个 class 中的位置创建一个设置器和获取器,然后这样做↓?
void fly(int x,int y){
objOfFly.fly(x,y);
objOfSwim.set(objOfFly.get(location));
}
void swim(int x,int y){
objOfSwim.swim(x,y);
objOfFly.set(objOfSwim.get(location));
}
我可以看到这是一个组合问题的一种方式。 你可以有不同的动作。
Monster{
int[] location;
}
你的行动:
SwimAction{
public void swim(Monster m, int x, int y){
//whatever you do to update the location.
m.location[0] += x;
m.location[1] += y;
}
}
然后是游泳怪物。
SwimMonster{
Monster base;
SwimAction swimAction;
public void swim( int x, int y ){
swimAction.swim(base, x, y);
}
}
同样,您可以编写更多动作。
SwimFlyMonster{
Monster base;
SwimAction s;
FlyAction f;
public void swim(int x, int y){
s.swim(base, x, y);
}
public void fly(int x, int y){
f.fly(base, x, y);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.