组合模式
//组合模式
//CopyRight(C) CAnca software Office.2006
//Created by CAnca.
import java.util.*;
public class ComponantMode{
public static void main(String[] args){
Componant Root = new compositionElement("Books");
Root.Add(new leaf("Java 设计模式"));
Root.Add(new leaf("C# 高级编程"));
Root.Add(new leaf("VB 程序设计"));
Componant js = new leaf("JavaScript 高级编程");
Root.Add(js);
Componant food = new compositionElement("Foods");
food.Add(new leaf("Apple"));
food.Add(new leaf("Banana"));
food.Add(new leaf("Pear"));
Root.Add(food);
Root.Display(1);
Root.Remove(js);
System.out.println();
Root.Display(1);
}
}
abstract class Componant{
protected String name;
protected final byte[] BLANK = "-----------------------------".getBytes();
public Componant(String name){
this.name = name;
}
public abstract void Add(Componant componant);
public abstract void Remove(Componant componant);
public abstract void Display(int indent);
}
class leaf extends Componant{
public leaf(String name){
super(name);
}
public void Add(Componant componant){
System.out.println("Leaf can't Add.");
}
public void Remove(Componant componant){
System.out.println("Leaf can't Remove.");
}
public void Display(int indent){
if(indent > BLANK.length - 1)indent = BLANK.length - 1;
System.out.println(new String(BLANK,0,indent) + " " + this.name);
}
}
class compositionElement extends Componant{
private ArrayList elements = new ArrayList();
public compositionElement(String name){
super(name);
}
public void Add(Componant componant){
this.elements.add(componant);
}
public void Remove(Componant componant){
this.elements.remove(componant);
}
public void Display(int indent){
if(indent > BLANK.length - 1)indent = BLANK.length - 1;
System.out.println(new String(BLANK,0,indent) + "+ " + this.name);
for(int i = 0 ; i < this.elements.size() ; i++){
((Componant)elements.get(i)).Display(indent + 2);
}
}
}