I have implemented a composite pattern with a composite class and a leaf class. The composite class contains an ArrayList of its children objects (which may be of type leaf or composite). Each class, both leaf and composite, have a boolean variable called 'satisfied'. My composite class can either be an 'and' or an 'or' class - if it's an 'and' class, it requires all of its children to be satisfied for it to be satisfied. If it's an 'or' class, it requires at least one of its children to be satisfied for it to be satisfied.
I am having trouble writing a recursive function 'isSatisfied' for the composite class to check whether all of its children are satisfied and therefore it would be too. It's recursive because if the composite object has children that are composite, it needs to check all of its children too etc. Here is what I've tried (it's incorrect). Any help would be appreciated.
public boolean isSatisfied(Component g) {
if (type.equals('and')) {
for (Component i : ((Composite) g).getChildren()) {
if (i instanceof Composite) { //it's a composite
isSatisfied(i);
} else { //it's a leaf
if (i.satisfied() == true) {
return true;
} else {
return false;
}
}
}
return false;
} else if (type.equals('or')) {
for (Component i : ((Composite) g).getChildren()) {
if (i instanceof Composite) {
isSatsified(i);
} else {
if (i.satisfied() == true) {
return true;
}
}
}
return false;
}
}
Aucun commentaire:
Enregistrer un commentaire