Ok so I have these interfaces and classes:
Code:
interface Tree extends Cloneable { int size(); }
class Fruit implements Tree {
@Override public int size() {
return this.size();
}
}
class Branch implements Tree 开发者_运维百科{
private List<Tree> children = new LinkedList<Tree>();
public List<Tree> getChildren() { return Collections.unmodifiableList(children); }
public void addChild(Tree tree) { children.add(tree); }
@Override public int size() {
int size = 0;
for(Tree tree: children) size += tree.size();
return size;
}
}
class Mango extends Fruit { /* intentionally left empty */ }
class Peach extends Fruit { /* intentionally left empty */ }
And I need to create code that structures this type of hybrid tree:
the trunk (main branch) of the tree
a branch with two mangoes
another branch with
a (sub)branch with two mangoes
one peach
I got the first part:
Branch trunk = new Branch();
But not sure how to code the next parts, can anyone help me with this?
You will need to create each of the other objects and add them to the trunk. Use the addChild(Tree tree)
method defined in Branch.
Some pseudocode:
make a branch for the trunk
make a branch
make two mangoes
add mangoes to branch
add the mango branch to the trunk
make a branch
make a peach
add peach to branch
make a sub-branch
make two mangoes
add mangoes to sub-branch
add sub-branch to branch
add branch to trunk
This is very procedural but is probably the most straightforward way given the code that you have. I would recommend that you consider making changes to the design if possible, but if this is a homework assignment you may be stuck with it.
The construction of this seems to more or less fit the composite pattern, as I read it.
精彩评论