Object Relationship Design

I'm just thinking about the concept of OO, which may seem rather trivial, but I don't know why I find it quite confusing.

In any case, I think, for example, if I have an Animal class and a Location class. And I allow one animal to be in one place at any time. So this seems like a 1 to 1 relationship. At the same time, I wish that the Animal and Location classes did not need some kind of bi-directional link, so that they were supported loosely coupled. If I have this:

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
}

From this, I foresee 2 problems.

-, , , . 1-1 , . . , . , , . , , , , , . , , , .

, , , , - Animal. newAnimal() . , , Animal . .

Java . , .

. !

+3
4
1.Location/Map in our case is a real world object and has boundaries.
2.Map can not hold more than one animal at any pont
3.An animal can not occupy more than one location

, .

. 2- . , ( ) , .

2D ( ), , - , .

, .

, A LocationManagerClass . , ""

+2

+ , / , . , /. Animal and Location ( ). : Map, DB, file ..

+1

, Animal Location?

Animal Animal. . , , ( ) , .

++ :

class Animal
{
    public:

            Animal(char *name);
            ~Animal();

            char *getName();
    private:

            char *name;

};

// Location, x, y. .

class Map
{

    private:

        Animal *animalLocation[10][10];


    public:
        //Note this function will check if any Animal exists at the specified (x,y). 
        void addAnimal(int x, int y, void *animal);
        void* getAnimal(int x, int y);

        Map();
        ~Map();

};

0

You can use something like the previous answers, but with a different data structure, and not with a 2D array. For example, a sparse array, an ordered list, or a hash table. This will provide a faster search, but will lead to a slower insertion or movement of animals. And he can still provide a claim for no more than one animal anywhere.

0
source

All Articles