在OO模型中添加双向关系的最佳实践 [英] Best practice for adding a bidirectional relation in OO model

查看:173
本文介绍了在OO模型中添加双向关系的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力想出一个在OO模型中添加双向关系的好方法。假设有一个客户可以发出许多订单,也就是说客户和订单类之间存在一对多关联,需要在两个方向上遍历:对于特定客户,应该可以告诉所有订单他们已下订单,对于订单,应该可以告诉客户。

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 one-to-many association between Customer and Order classes that need to be traversable in both directions: for a particular customer it should be possible to tell all orders they have placed, for an order it should be possible to tell the customer.

这是一段Java代码,虽然这个问题主要与语言无关:

Here is a snippet of Java code, although the question is largely language-agnostic:

class Customer {
 private Set orders = new HashSet<Order> ();

        public void placeOrder (Order o) {
     orders.add(o);
            o.setCustomer(this);
 }
}

class Order {
 private Customer customer;
        public void setCustomer (Customer c) {
  customer = c;
 }
}

鉴于模特有人可以很容易致电:

What buggers me is that given the model someone could easily call:

o.setCustomer(c);

而非正确

c.placeOrder(o);

形成单向链接而不是双向链接。

forming unidirectional link instead of bidirectional one.

仍然在学习OOP,任何人都可以请求帮助解决这个问题的惯用和实用方法,而不是诉诸反思或花哨的框架(无论如何都要依靠反思)。

Still learning OOP, could anyone please help with what would be an idiomatic and practical way of solving this problem without resorting to "reflection" or fancy frameworks (that would anyway rely on reflection).

PS还有一个类似的问题:在我的java模型中管理双向关联,但是我觉得它没有回应我的请求。

P.S. There is a similar question: Managing bidirectional associations in my java model, however I don't feel it answers my plea.

P.S.S。任何在db4o之上实现商业模式的现实项目源代码的链接都非常感谢!

P.S.S. Any links to source code of real-life projects implementing business model on top of db4o are greatly appreciated!

推荐答案

首先,除非你计划在客户之间移动订单,我认为你不应该提供 setCustomer()方法,客户应该是构造函数的参数并保持不变。

first, unless you plan on moving orders between customers, I think you shouldn't provide a setCustomer() method, the customer should be a parameter for the constructor and leave it unchanged.

然后,用户不应该访问构造函数,只使用所有者的工厂方法

then, the constructor shouldn't be accessible for the user, only use the factory method of Owner.

这篇关于在OO模型中添加双向关系的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆