java设计模式----组合模式 weir 2015-04-21 19:51:47.0 java,设计模式 1524 从组合模式的结果来看 好像是专门为树状结构数据而生的。说实话还真不知道还有什么结构的数据可以用组合模式。 我觉得这种设计模式目标特定,简单实用问题不大,如果对数据要求过多,此模式就麻烦了。需要处理各种需求变化。 package com.weir.composite; /** * 抽象类 * @author Administrator * */ public abstract class Component { public abstract void a(String s); public void addChild(Component childComponent){ throw new UnsupportedOperationException("对象不支持这个功能"); } public void removeChild(Component childComponent){ throw new UnsupportedOperationException("对象不支持这个功能"); } public Component getChildren(int index) { throw new UnsupportedOperationException("对象不支持这个功能"); } } package com.weir.composite; /** * 末端对象 或者 叶子对象 * @author Administrator * */ public class A1 extends Component{ private String name = ""; public A1(String name){ this.name = name; } @Override public void a(String s) { System.out.println(s+"--"+name); } } package com.weir.composite; import java.util.ArrayList; import java.util.List; /** * 中间对象 * @author Administrator * */ public class A extends Component{ private List<Component> childs = null; private String name = ""; public A(String name){ this.name = name; } @Override public void a(String s) { System.out.println(s+"++"+name); if (childs!=null) { s+="/"; for (Component component : childs) { component.a(s); } } } public void addChild(Component child) { if (childs==null) { childs = new ArrayList<Component>(); } childs.add(child); } public void removeChild(Component child) { if (childs!=null) { childs.remove(child); } } public Component getChild(int index) { if (childs!=null) { if(index>=0 && index<childs.size()){ return childs.get(index); } } return null; } } package com.weir.composite; public class Client { public static void main(String[] args) { Component root = new A("root"); Component a1 = new A("a1"); Component a2 = new A("a2"); A1 a11 = new A1("a11"); A1 a12 = new A1("a12"); A1 a23 = new A1("a23"); A1 a24 = new A1("a24"); root.addChild(a1); root.addChild(a2); a1.addChild(a11); a1.addChild(a12); a2.addChild(a23); a2.addChild(a24); root.a(""); } } 结果: ++root /++a1 //--a11 //--a12 /++a2 //--a23 //--a24 如果单单是作为读取来操作,该模式会显得很简单,如果在变化中读取数据的话,此模式就显得操作和判断处理的复杂,需要考虑各种逻辑的变化关系。