合成模式属于对象的结构模式,有时又叫做“部分——整体”模式。合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式可以使客户端将单纯元素与复合元素同等看待。通常用树结构来表示这种部分、整体的关系:
1 import java.util.ArrayList; 2 import java.util.List; 3 4 //抽象构建接口 5 interface Component{ 6 public void printNode(String str); 7 } 8 9 //树枝类 10 class Composite implements Component{ 11 12 private List<Component> childs = new ArrayList<Component>(); 13 private String name; 14 15 public Composite(String name){ 16 this.name = name; 17 } 18 19 public void add(Component child){ 20 childs.add(child); 21 } 22 23 public void remove(int index){ 24 childs.remove(index); 25 } 26 27 public List<Component> getChild(){ 28 return childs; 29 } 30 31 @Override 32 public void printNode(String str) { 33 System.out.println(str + "+" + name); 34 if(childs != null){ 35 str += " "; 36 for(Component c: childs) 37 c.printNode(str); 38 } 39 } 40 41 } 42 43 //树叶类 44 class Leaf implements Component{ 45 46 private String name; 47 48 public Leaf(String name){ 49 this.name = name; 50 } 51 52 @Override 53 public void printNode(String str) { 54 System.out.println(str + "-" + name); 55 } 56 57 } 58 59 public class MyTest { 60 61 /** 62 * @param args 63 */ 64 public static void main(String[] args) { 65 Composite root = new Composite("根"); 66 Composite c1 = new Composite("树枝1"); 67 Composite c2 = new Composite("树枝2"); 68 69 Leaf leaf1 = new Leaf("树叶1"); 70 Leaf leaf2 = new Leaf("树叶2"); 71 Leaf leaf3 = new Leaf("树叶3"); 72 73 root.add(c1); 74 root.add(c2); 75 c1.add(leaf1); 76 c1.add(leaf2); 77 c2.add(leaf3); 78 } 79 80 }