Maintaining a two way relationship between classes

前端 未结 6 597
萌比男神i
萌比男神i 2021-02-02 00:34

It is pretty common, especially in applications with an ORM, to have a two way mapping between classes. Like this:

public class Product
{
    private List

        
6条回答
  •  情歌与酒
    2021-02-02 01:22

    In the past I've added "link" methods, i.e., instead of "setting" the Price on a Product, you link the product and the price.

    public void linkPrice(Price toLink) {
        this.price = toLink;
        toLink.setProduct(this);
    }
    

    (if you use setPrice to do this, then setProduct would also do this, and they would forever call each other in the second line, hence I create an explicit link method instead of using the setters and getters. Indeed the setter could be package protected.

    YMMV, your situation could be different.

提交回复
热议问题