Mega Code Archive

 
Categories / Java Tutorial / Design Pattern
 

Flexible structure Composite

import java.util.ArrayList; import java.util.Iterator; interface Movable {   void operation(); } class File implements Movable {   private String name;   public File(String name) {     this.name = name;   }   public String toString() {     return name;   }   public void operation() {     System.out.println(this);   } } class FileTree extends ArrayList<Movable> implements Movable {   private String name;   public FileTree(String name) {     this.name = name;   }   public String toString() {     return name;   }   public void operation() {     System.out.println(this);     for (Iterator<Movable> it = iterator(); it.hasNext();)       it.next().operation();   } } public class CompositeStructure {   public static void main(String args[]) {     FileTree root = new FileTree("root");     root.add(new File("Leaf1"));     FileTree c2 = new FileTree("Node1");     c2.add(new File("Leaf2"));     c2.add(new File("Leaf3"));     root.add(c2);     c2 = new FileTree("Node2");     c2.add(new File("Leaf4"));     c2.add(new File("Leaf5"));     root.add(c2);     root.operation();   } }