store many of relation 1:1 between various type of objects : decoupling & high performance

前端 未结 6 1241
夕颜
夕颜 2021-02-01 08:26

I have 300+ classes. They are related in some ways.

For simplicity, all relation are 1:1.
Here is a sample diagram.

(In real case, there are aroun

6条回答
  •  醉梦人生
    2021-02-01 09:18

    Based on the requirements, if you have only one-to-one relations, then it sounds to me like a graph. In this case, if it is densely populated (there are many relations), I would use the matrix representation of the graph. In the tables below, I have associated numbers 0 through 4 to the entities (Hen, Cage, Food, Egg and Chick) respectively. If the relation Hen - Egg exists, then the matrix will have a 1 at the position matrix[0][3], if it doesn't then the value would be 0 (you can choose values of your choice to decide how to tell when the relation exists or doesn't). If the relations are undirected, then you only need one side of the matrix (the upper triangle, for example).

    +---------------------------------+
    | Hen | Cage | Food | Egg | Chick |
    +---------------------------------+
    |  0  |  1   |  2   |  3  |   4   |
    +---------------------------------+
    
          0   1   2   3   4
        +--------------------+
      0 | 0 | 1 | 0 | 1 | 1  |
        +---+---+---+---+----+
      1 | 0 | 0 | 0 | 1 | 1  |
        +---+---+---+---+----+
      2 | 0 | 0 | 0 | 0 | 1  |
        +---+---+---+---+----+
      3 | 0 | 0 | 0 | 0 | 1  |
        +---+---+---+---+----+
      4 | 0 | 0 | 0 | 0 | 0  |
        +--------------------+
    

    The downside of this solution hides in the memory usage, especially if the matrix contains a lot of 0's (relations that don't exist); you would be unnecessarily occupying a lot of space. In this case you may use the linked-list representation of the graphs.

提交回复
热议问题