我恰巧考虑到一个可能听起来很琐碎但我不知道为什么我觉得相当困惑的面向对象概念。
无论如何,举个例子,如果我有一个动物类和一个位置类。我只允许一只动物在任何时候都在一个位置上。所以这有点像1对1的关系。同时,我希望动物和位置类不需要某种双向引用,以便它们保持松耦合。如果说我有这个:
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
}
从这里,我预见到了两个问题。
首先,因为我的位置不知道是否已经有动物在上面,许多动物都可以指向地图数组上的同一位置。这将违反我想要的1-1多重性约束。在我的情况下,我让动物拥有位置。这可能是发生这种情况的原因。如果我让位置拥有动物,这个问题就可以解决。但是,在某种情况下,如果我想知道我的动物在哪里,我需要遍历整个地图才能找到其中一个动物的位置?或者,我可以保持双向引用,但这会导致类高度耦合。
我感觉第二个问题可能是动物类中的设计问题。我有一个静态的newAnimal()方法来实例化新动物。我这样做是因为我认为允许调用者直接从构造函数创建新的Animal实例可能会导致超出范围的坐标输入。但我仍然觉得设计非常尴尬。
我在我的示例中使用Java代码。我正在考虑类对象本身内部的设计,而没有涉及数据库。
任何改进我提出的两个问题的建议都可以很好地解决。谢谢!