我只是碰巧想到了一个听起来很微不足道的 OO 概念,但我不知道为什么我觉得它很混乱。
无论如何,我正在考虑例如,如果我有一个 Animal 类和一个 Location 类。而且我只允许一只动物在任何时候出现在一个位置。所以这有点像一对一的关系。同时,我希望 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 拥有 Location。这可能是发生这种情况的原因。如果说我让位置拥有动物,这可以解决。但是如果我想知道我的动物在哪里,我需要遍历整个地图才能找到我的动物的位置之一?或者,我可以保留双向引用,但这会导致类高度耦合。
我觉得可能是一个问题的第二个问题是 Animal 类的设计。我有一个静态 newAnimal() 方法来实例化新动物。我这样做是因为我认为允许调用者直接从构造函数创建新的 Animal 实例可能会允许超出范围的坐标输入。但我还是觉得这个设计很尴尬。
我在我的示例中使用 Java 代码。而且我正在考虑类对象本身的设计,并且还没有涉及数据库。
任何改善我提出的两个问题的建议都可能很棒。谢谢!