Where to store class-relationship information?
-
22-06-2021 - |
문제
Assume, we have classes A_1
to A_n
and classes B_1
to B_n
.
Each A_i
has relationships (abstract spoken; a relation could be 'A_4 likes B_2') to a set of B_j
's and the same the other way round.
Question: Where is a good place to store the relationship information ? Is there a good pattern for this kind of problem ?
Solution 1: Each A_i
has a list field store the B_j
's it has a relation with.
Solution 2: Each B_i
has a list field store the A_j
's it has a relation with.
Solution 1 and 2 are basically the same.
Solution 3: Store the information in a third 'information' class, e.g. as a matrix.
올바른 솔루션이 없습니다
다른 팁
No matter which one you choose between Solution 1 and Solution 2 some information about what a class likes is only stored in another class, which seems a bit backwards.
Therefore, I would definitely go for a separate RelationKeeper class, something like this:
public enum RelationType {
LIKES,HATES...
}
public class Relation {
RelationType type;
Class relatedClass; //Or in what type and form this is stored
}
public class RelationKeeper {
public List<Relation> getRelationsFor(Class c) {
}
public void setRelationsFor(Class c, List<Relation> relations) {
}
public void addRelationFor(Class c, Relation relation) {
}
...etc
}
This way you can customize and change the internal storage method to fit your needs, depending on if you want to be able to retrieve only "outgoing" relations of a class or if you also want to be able to fetch "inbound" relations.