组合模式的简单应用
public abstract class Component {protected String name;protected String type;protected void setType(String type) {this.type=type;}protected final String getType() {return type;}protected void setName(String name) {this.name=name;}protected final String getName() {return name;}public abstract void print();}import java.util.ArrayList;import java.util.Iterator;public class Composite extends Component {protected ArrayList<Component>list=new ArrayList<Component>();public Composite() {}protected void add(Component c) {this.list.add(c);}protected void remove(Component c) {if(this.list.isEmpty()==false) this.list.remove(c);}protected void remove(int index) {if(index <0 || index>=this.getSize()) {System.out.println("out of bound!");return;}else this.list.remove(index);}protected final Component getComponent(int index) {if(index <0 || index>=this.getSize()) return null;else return this.list.get(index);}protected final int getSize() {return this.list.size();}@Overridepublic void print() {// TODO Auto-generated method stubSystem.out.println("I am: "+this.getType());System.out.println("My name is: "+this.getName());Iterator<Component>iterator=list.iterator();while(iterator.hasNext()) {iterator.next().print(); System.out.println("I belong to: "+this.getName());}}}public class Leaf extends Component {public Leaf(String name) {this.setName(name);this.setType("leaf");}@Overridepublic void print() {// TODO Auto-generated method stubSystem.out.println("I am: "+this.getType());System.out.println("My name : "+this.getName());}}public class Branches extends Composite {public Branches(String name) {super();this.setName(name);this.setType("Branches");}public Branches() {}}public class Tree extends Branches {public Tree(String name) {super();// TODO Auto-generated constructor stubthis.setName(name);this.setType("Tree");}}public class Client {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubLeaf leaf1=new Leaf("leaf1");Leaf leaf2=new Leaf("leaf2");Leaf leaf3=new Leaf("leaf3");Leaf leaf4=new Leaf("leaf4");Branches branches1=new Branches("branches1");Branches branches2=new Branches("branches2");branches1.add(leaf1);branches1.add(leaf2);branches2.add(leaf3);branches2.add(leaf4);Tree tree=new Tree("Binary Tree");tree.add(branches1);tree.add(branches2);tree.print();}}
测试:
I am: TreeMy name is: Binary TreeI am: BranchesMy name is: branches1I am: leafMy name : leaf1I belong to: branches1I am: leafMy name : leaf2I belong to: branches1I belong to: Binary TreeI am: BranchesMy name is: branches2I am: leafMy name : leaf3I belong to: branches2I am: leafMy name : leaf4I belong to: branches2I belong to: Binary Tree