我只是想了解一个面向对象的概念,这听起来很琐碎,但我不知道为什么我觉得它很混乱。对象关系设计
无论如何,我想,例如,如果我有一个动物类和位置类。我只允许一只动物随时在一个地方。所以它就像是一对一的关系。同时,我希望Animal和Location类不需要某种双向引用,以便它们保持松散耦合。如果说我有这个:
class Animal {
private Location loc;
public Animal(int x, int y) {
loc = new Location(x,y);
}
public static newAnimal(Location[][] map, int x, int y) {
if(map[x][y] != null) {
return new Animal(x, y);
} else return null;
}
class Location extends Point {
public Location(int x, int y) {
super(x, y);
}
}
public static void main(String[] args) {
//populates a map
Location[][] map = new Location[10][10];
for(int x=0; x<10; x++) {
for(int y=0; y<10; y++) {
map[x][y] = new Location(x, y);
}
}
Animal dog = new Animal(2, 4); //dog is at location 2,4
Animal cat = new Animal(5, 6); //cat is at location 5,6
//But this does not restrict a constraint requirement that there should only be one animal at any one point
Animal horse = new Animal(2, 4); //now, horse is at the same location as dog but we only wanted one location to have one animal
Animal rabbit = Animal.newAnimal(map, 20, 50); //rabbit is null because it is out of the map size
}
从这里,我预见到2个问题。
首先,因为我的位置不知道动物是否已经在它上面,所以许多动物都可以指向地图阵列上的相同位置。这会违反我想要的1-1多重约束。就我而言,我让动物拥有这个位置。这可能是这种情况发生的原因。如果说我让位置拥有动物,这可以解决。但是如果我想知道我的动物在哪里,我需要遍历整个地图才能找到我的动物的位置在哪里?或者,我可以保留一个双向引用,但这会导致类被高度耦合。
我觉得可能是一个问题的第二个问题是Animal类中的设计。我有一个静态的newAnimal()方法来实例化新的动物。我这样做是因为我认为允许调用者直接从构造函数创建新的Animal实例可能会允许超出范围的坐标输入。但我仍然觉得设计非常尴尬。
我在示例中使用了Java代码。我认为类内的设计本身并不涉及数据库。
改善我提出的两个问题的任何建议都可能很好。 谢谢!
一棵树不包含猴子,而猴子也知道他在哪一棵树,甚至可能如何计算猴子时尚之后剩下多少香蕉? – Affe 2011-06-03 06:57:41
@Affe,感谢您添加评论。我仍然有点困惑。你能再详细一点吗?谢谢! – Carven 2011-06-03 07:14:19
这是我的方式来说,如果您的业务/应用程序域包含两个共享状态的事物,它们在定义上是耦合的。如果试图模仿他们,那么跳过篮球有什么好处呢? – Affe 2011-06-03 07:19:11