Programming a one-to-many relationship

后端 未结 8 712
醉话见心
醉话见心 2020-12-25 08:16

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

相关标签:
8条回答
  • 2020-12-25 08:34

    There's no 100% surefire way to maintain the integrity.

    The approach which is usually taken is to use one method to construct the relationship, and construct the other direction in that same method. But, as you say, this doesn't keep anyone from messing with it.

    The next step would be to make some of the methods package-accessible, so that at least code which has nothing to do with yours can't break it:

    class Parent {
    
      private Collection<Child> children;
    
      //note the default accessibility modifiers
      void addChild(Child) {
        children.add(child);
      }
    
      void removeChild(Child) {
        children.remove(child);
      }
    }
    
    class Child {
    
       private Parent parent;
       public void setParent(Parent parent){
         if (this.parent != null)
           this.parent.removeChild(this);
         this.parent = parent;
         this.parent.addChild(this);
       }
    }
    

    In reality, you won't often model this relationship in your classes. Instead, you will look up all children for a parent in some kind of repository.

    0 讨论(0)
  • 2020-12-25 08:34

    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.

    0 讨论(0)
提交回复
热议问题