开发者

Mapping vs composition

If I have two classes with a one-to-one relationship, when's a good time to use mapping.

class A { ... }
class B { ... }
class C { 
    Map<A,B> a2b;
}
开发者_开发问答

And when's a good time to use composition?

class A {
    B myB;
}
class B { ... }

Would the answer change if the relationship was one-to-many and many-to-many?


This depends on how widespread this A to B relationship is used throughout the project.

If lots of different areas of the project will need to know the B associated with A, then it is best if this is simply a part of the A object. On the other hand, if this association is only used in one part of the project, then you should create the HashMap in that part of the project to store the relationship.

This answer does not change if it's a one-to-many or many-to-many relationship.


Using a Map will increase complexity of the whole thing.

This because in your example one of the two classes (A) owns the other, this is true either for composition (since you need the A to retrieve its B) either for the mapping (since you need the key A for value B).

So if there's not an explicit need to used a map, just avoid it.

For the cases 1:N, M:N you should always consider what kind of operations you will need to do on the objects, since having a third object that just manages the mapping between the A and B is not a really OO solution, you could use composition.

One-to-Many can be modeled with a List<B> inside A while Many-to-Many is the only case in which having a mapping could be good, since otherwise you would have to explore both objects to understand their mappings.

Shortly: if you will access the data from a A perspective (A owns B) then you don't need to have an external mapping, otherwise you will but it should be bidirectional (two hashmaps).


The map is good for many-to-many relationships (like join tables in database design). As long as your one-to-one or one-to-many relation does not need special attributes, there's no need to use a third class (this third class would model the relation itself).

Make an association, maybe a bi-directional one, if you need to look from both directions:


public class A {
  private B b;
  public A(B b){
    this.b = b;
    b.setA(this);  // for bi-directional association
  }
}

public class B {
  private A a;
  public B(){};
  public void setA(A a) {
    this.a=a;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜