0

让我们考虑一个类 'Human' -->(1..*) 'Human' ,其中 Human 是一个超类型。假设它有像'Male','Female','SociallyPathologicalMale'等子类。基本关联b / w 2实体仍然常见,子类型定义名称和关联的约束,但基本关系仍然是m:nb / w 2人类实体。例子:-

  • '男' -->(1:1)('妻子'(关系名)) '女'

  • '女'-->(1:1)('老公') '男'

  • 'SociallyPathologicalMale'-->(1:0)('friends') 'Male'

    [编辑 13/12/2011] - 如果说我们必须在 java 中实现它,那么有哪些最佳实践可以使关联重用成为可能?

假设我们从基类开始:-

 class Human{
  private List<Human> relationships; // in a subclass this field, could 
//  this generically be represented ?? 
}

就像是

   class Man extends Human{
    private List<Woman> relationships;//should be 0 or 1
    }

现在,在 Man(或任何其他子类)中重新定义关系字段这一事实可以在结构上强制执行,即在定义任何子类时,我应该强制定义关系。java中的这种构造是否可能?有没有其他语言可以轻松做到这一点?

4

2 回答 2

0

你应该从你的场景中回顾两件重要的事情:

1) 字段不能被子类重新定义。这不是语言(Java)的限制,而是合理的概念强加。字段定义了对象什么,方法定义了对象的作用方式。唯一可以重新定义的是对象如何完成事情,但不允许更改超类什么或什么。(我说的是“对象”,但请记住,我的意思是“类的实例”,因为您实际上是在类主体中定义行为)。

2)您必须使关系成为一流的对象。因为使用范式为您提供的内容是不够的:“是一个”和“有一个”。正如 Darren Burgess 所说,范式为您提供了两种概念关系:“是一个”和“有一个”。对于Human->ManHuman->Woman示例,您可以使用继承,换句话说,“is a”。Man 类扩展了 Human ,因为 Man 是 Human。困难在于“具有”关系,因为 OOP 不允许您指定基数,并且您还想在关系上指定名称。为简单起见,让我们将关系定义为二元关系。例如,一个男人有一个妻子或一个女人有一个丈夫John 是 Tom 和 Linda 的父亲,我们将定义两个关系:John 是 Tom 的父亲John 是 Linda 的父亲。您的方法的问题是您指定了一个男人列表和一个女人列表。但是,人类实际上拥有的是关系集合。设计将如下所示:

public Human {
    private Collection<Relationship> relationships;
}

public Relationship {
    private Human party; // We are defining only relationships between humans.
    private Human counterparty;
    private String name; // e.g., "is the Husband of" and "is the Wife of".
}

当事人和交易对手是关系的成员,关系的对象实例将代表一个人与另一个人的关系。

定义特定的行为会更加特别。例如,一个SociallyPathologicalMale将没有任何关系。您可以将以下方法添加到Human

public void addRelationship(Relationship newRelationship) {
    relationships.add(newRelationship);
}

SociallyPathologicalMale 类(扩展了 Male)将继承该方法并将重新定义如下:

public void addRelationship(Relationship newRelationship) { // 此处无事可做。}

基本上,根据定义,由于 SociallyPathologicalMale 无法建立任何关系,因此您可以通过编程方式禁用超类Male提供的能力。

我希望它能澄清你的问题。

于 2013-11-17T10:25:06.870 回答
0

我将使用的两种实现方法是继承和组合。

is a关系用继承表示,关系has a用组合表示。

继承和组合都允许您在新类中放置子对象。代码重用的两个主要技术是类继承和对象组合。

Inheritance

class Human {
//some code
}
class Male extends Human {
//some code
}

Composition

class Male
{
     Wife mrs = new Wife();
}
于 2011-12-02T22:42:11.370 回答