设计模式:组合模式
组合模式(Composite)相对比较简单;但是在关于设计的地方很多都用到了这种模式。例如,SWT,Eclipse ?Workspace等等。组合模式一般用来生成一个可以通过同一方法来访问不同层级的树。
1、类图
?
下面的代码例子实现了如下树状数据结构。
?2、代码实例
import java.util.List;import java.util.ArrayList; //Componentinterface Component { public void show();} //Compositeclass Composite implements Component { private List<Component> childComponents = new ArrayList<Component>(); public void add(Component component) { childComponents.add(component); } public void remove(Component component) { childComponents.remove(component); } @Overridepublic void show() {for (Component component : childComponents) { component.show(); }}} //leafclass Leaf implements Component {String name;public Leaf(String s){name = s;} public void show() { System.out.println(name); }} public class CompositeTest { public static void main(String[] args) { Leaf leaf1 = new Leaf("1"); Leaf leaf2 = new Leaf("2"); Leaf leaf3 = new Leaf("3"); Leaf leaf4 = new Leaf("4"); Leaf leaf5 = new Leaf("5"); Composite composite1 = new Composite(); composite1.add(leaf1); composite1.add(leaf2); Composite composite2 = new Composite(); composite2.add(leaf3); composite2.add(leaf4); composite2.add(leaf5); composite1.add(composite2); composite1.show(); }}
?3、实际应用
Android中的视图描画过程。ViewGroup中的dispatchDraw,统一调用View的draw方法,来完成树状视图的描画。?