HasA关系最好的实施方式?

时间:2014-01-28 10:33:31

标签: java

我有以下课程。

One.java

public class One implements Serializable{

  private static final long serialVersionUID = 6761261711393553478L;

  private String name;
  private String id;

  //public getters and setters

}

Two.java

 public class Two implements Serializable{

      private static final long serialVersionUID = 5671261711393553478L;

      private String rawId;
      private String genericId;

      //public getters and setters

    }

Three.java

public class Three  implements Serializable{

      private static final long serialVersionUID = 1231261711393553478L;

      private String extension;
      private String shift;

      //public getters and setters

    }

Container.java

public class Container implements Serializable {

  private static final long serialVersionUID = 2345261711393553478L;

  private One one;
  private Two two;
  private Three three;

  //public getters and setters


}

现在客户端将使用setter和getter填充Container.java。你有什么建议吗? 我的实施是否正确?您是否建议进行任何更改?

谢谢!

2 个答案:

答案 0 :(得分:1)

这正是hasA关系的含义 - Container 三个成员 - OneTwo和{{1 }}

我要介绍的唯一一个小修正是改变Three,所以它也是Container

所以而不是:

Serializable

你应该

public class Container {
    ...

答案 1 :(得分:1)

是的,你的设计很好。

您正在使用 Composition ,这是has-a关系的面向对象概念。

为方便起见,您可能还想为Container.java添加构造函数,如下所示:

public Container(One one, Two two, Three three) {
    this.one = one;
    this.two = two;
    this.three = three;
}