1 package test_26_1; 2 3 public abstract class Component { 4 5 private String name; 6 7 public Component() { 8 9 } 10 11 public Component(String name) { 12 this.name = name; 13 } 14 15 public abstract void compositeAdd(Component c); 16 17 public abstract void compositeRemove(Component c); 18 19 public abstract void leafMethod(); 20 21 public String getName() { 22 return name; 23 } 24 25 }
1 package test_26_1; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class Composite extends Component { 7 8 List<Component> list = new ArrayList<Component>(); 9 10 public Composite() { 11 12 } 13 14 public Composite(String name) { 15 super(name); 16 } 17 18 @Override 19 public void compositeAdd(Component c) { 20 21 list.add(c); 22 } 23 24 @Override 25 public void compositeRemove(Component c) { 26 27 list.remove(c); 28 } 29 30 @Override 31 public void leafMethod() { 32 33 System.out.println(getName() + " Composite leafMethod()"); 34 35 for (Component component : list) { 36 component.leafMethod(); 37 } 38 } 39 40 }
1 package test_26_1; 2 3 public class Leaf extends Component { 4 5 public Leaf() { 6 7 } 8 9 public Leaf(String name) { 10 super(name); 11 } 12 13 @Override 14 public void compositeAdd(Component c) { 15 16 } 17 18 @Override 19 public void compositeRemove(Component c) { 20 21 } 22 23 @Override 24 public void leafMethod() { 25 26 System.out.println(getName() + " Leaf leafMethod()"); 27 } 28 29 }
1 package test_26_1; 2 3 public class ComponentTest { 4 5 public static void main(String[] args) { 6 7 Composite root = new Composite("root"); 8 Composite branch1 = new Composite("branch1"); 9 Composite branch2 = new Composite("branch2"); 10 Leaf leaf1_1 = new Leaf("leaf1_1"); 11 Leaf leaf1_2 = new Leaf("leaf1_2"); 12 Leaf leaf2_1 = new Leaf("leaf2_1"); 13 Leaf leaf2_2 = new Leaf("leaf2_2"); 14 15 branch1.compositeAdd(leaf1_1); 16 branch1.compositeAdd(leaf1_2); 17 branch2.compositeAdd(leaf2_1); 18 branch2.compositeAdd(leaf2_2); 19 20 root.compositeAdd(branch1); 21 root.compositeAdd(branch2); 22 23 root.leafMethod(); 24 } 25 }
结果如下:
root Composite leafMethod()
branch1 Composite leafMethod()
leaf1_1 Leaf leafMethod()
leaf1_2 Leaf leafMethod()
branch2 Composite leafMethod()
leaf2_1 Leaf leafMethod()
leaf2_2 Leaf leafMethod()