Call method recursively
Composite Pattern can represent a tree structure
(If it becomes a tree structure, you can consider Composite) </ font>
Check with the following class structure
class | Explanation |
---|---|
interface face |
Handle different objects with face type |
sam.class | implement face |
samList.class | implement face Hold List and call recursively |
user(Main.class) | Check the operation |
Below is the sample code
interface_face
interface face{void print();}
sam.class
class sam implements face{
public void print(){
System.out.println("."+this);
}}
samList.class
class samList implements face{
List list = new ArrayList();
void add(face fc){list.add(fc);}
public void print(){
Iterator it = list.iterator();
while(it.hasNext()){
face fit = (face) it.next();
System.out.print("/"+fit);
fit.print(); //sam if fit is sam type.class print()Is called and this does not recurse
//print samList if fit is of type samList()Is called recursively
}
}
}
user(Main.class)
public static void main(String[] args){
samList sam1 = new samList();
samList sam2 = new samList();
samList sam3 = new samList();
sam2.add(new samList());
sam2.add(new sam());
sam3.add(new samList());
sam3.add(new sam());
sam1.add(sam2);
sam1.add(sam3);
sam1.print();
}}
Recommended Posts