在Java中创建继承/组合结构

时间:2017-12-11 16:18:24

标签: java oop

我正在寻找有关以下情况的方法的建议。我认为继承结构将有助于减少同步代码。关于创建此模型的理想方法的任何建议或指向类似的示例。

模型如下所示。

有几位爷爷奶奶。 GrandParent可以有几个父母,同样父母可以有几个孩子。似乎有两个"继承"结构,一个用于父/子,另一个用于" IncomeStatements"。

" grandIncomeStatement"和#34; parentIncomeStatement"是其子女的累积损益表以及自己的IncomeStatement。只要对" myIncomeStatement"进行任何更改,他们就必须同步。

现在,我创建了一个"类IS(IncomeStatement)"它具有通用属性,没有任何继承和编写的代码更改 - 每个级别的IncomeStatements。

class GrandParent {
   ObjectIS myIncomeStatement;
   ObjectIS grandIncomeStatement;
}
class Parent {
   ObjectIS myIncomeStatement;
   ObjectIS parentIncomeStatement;
}
class Child {
   ObjectIS myIncomeStatement;
}

1 个答案:

答案 0 :(得分:2)

另一种方法是Person并且它有孩子列表。

public class Person {
    List<Person> children;
    ObjectIS myIncomeStatement;
    ObjectIS familyIncomeStatement;

    public ObjectIS getFamilyIncomeStatement() {
        ObjectIS is = new ObjectIS();
        for(Person p: children) {
            is.income += p.familyIncomeStatement.income;
        }
        is.income += this.myIncomeStatement.income;
        return is;
    }
}

// sample objectIS class
public class ObjectIS {
    private int income;
}

编辑:所以你可能有一个递归的方式来计算familyIncome(你显然会有一个更严格的访问控制,正确的getter / setter)

相关问题