Programming a one-to-many relationship

2019-02-01 13:32发布

So I am surprised that doing a search on google and stackoverflow doesn't return more results.

In OO programming (I'm using java), how do you correctly implement a one-to-many relationship?

I have a class Customer and class Job. My application is for a fictious company that completes jobs for customers. My current implementation is so that the Job class doesn't have anything to do with the Customer class, there is no reference to it at all. The Customer class uses a collection and methods to hold, retrieve and modify information about the Jobs that have been assigned by and/or completed for a customer.

The question is, what if I'd want to find out for which customer a particular Job has been done? I've only found this article that's relevant: http://www.ibm.com/developerworks/webservices/library/ws-tip-objrel3/index.html.

According to the implementation of the author, I would let the Job constructor take a Customer parameter, and store it so I can retrieve it. However, I see no guarantee at all that this model can be consistent. There are no restirctions to set the related customer for a job as a customer that the job was not for, and add jobs to customers that were done for someone else. Any help on this would be appreciated.

8条回答
唯我独甜
2楼-- · 2019-02-01 14:05

I know this is late but I think another way to this would be to look at the problem a bit differently. Since customer holds a collection of all jobs assigned by or completed for a customer, you could consider the job class to be a sub class of customer with extra information of having all the jobs completed by the customer. Then you would only have to maintain customer id in the main class and it would be inherited. This design would ensure that each job can be linked to a customer. Also if for a customer you want to find out how many jobs are present that too also would be got.

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-01 14:05

I am sorry I know this is very late but I have come across a similar problem where I feel the best solution is to follow a inheritance model. Think of job as being jobs done/asisgned by a particular customer. So in that case the Customer would be a super class with the Job(Lets call is customer job) being a sub class since a Job cannot exists without a customer. A customer would also have a list of jobs primarily for ease of data fetching. Intutively this does not make sense since Job and Customer done seem to have any relation, however once you see that Job cannot exist without a customer, it just becomes an extension of customer.

查看更多
登录 后发表回答