Best practice for adding a bidirectional relation in OO model

前端 未结 5 1456
無奈伤痛
無奈伤痛 2021-02-04 09:24

I\'m struggling to come up with a good way of adding a bidirectional relation in OO model. Let\'s say there is a Customer who can place many Orders, that is to say there is a on

5条回答
  •  时光说笑
    2021-02-04 09:47

    I think the best way in this case is to delegate the responsibility for wiring to another class:

    class OrderManager {
        void placeOrder(Customer c, Order o){
            c.addOrder(o);
            o.setCustomer(c);
        }
    }
    
    class Customer {
        private Set orders = new LinkedHashSet();
        void addOrder(Order o){ orders.add(o); }
    }
    
    class Order {
        private Customer customer;
        void setCustomer(Customer c){ this.customer=c; }
    }
    

提交回复
热议问题