合成模式
合成模式
合成模式属于对象的结构模式,有时又叫做“部分–整体”模式。合成模式将对象组织到树结构中国,可以用来描述整体与部分的关系,合成模式可以使客户端将单纯元素与复合元素同等看待;
涉及到三个角色;
安全模式的代码:
抽象构件;
package compositeSafe; public interface Component { public void printStruct(String preStr); }
树枝构件;
package compositeSafe; import java.util.ArrayList; import java.util.List; public class Composite implements Component{ public Composite() { // TODO Auto-generated constructor stub } private List<Component> childComponents = new ArrayList<Component>(); private String name; public Composite(String name){ this.name = name; } public void addChild(Component child){ childComponents.add(child); } public void removeChild(int index){ childComponents.remove(index); } public List<Component> getChild(){ return childComponents; } public void printStruct(String preStr){ System.out.println(preStr + "+" + this.name); if(this.childComponents != null){ preStr += " "; for(Component c: childComponents){ c.printStruct(preStr); } } } }
树叶构件;
package compositeSafe; public class Leaf implements Component{ public Leaf() { // TODO Auto-generated constructor stub } private String name; public Leaf(String name) { this.name = name; } public void printStruct(String preStr){ System.out.println(preStr + "-" + name); } }
客户端;
package compositeSafe; public class Client { public Client() { // TODO Auto-generated constructor stub } public static void main(String[] args){ Composite root = new Composite("服装"); Composite c1 = new Composite("男装"); Composite c2 = new Composite("女装"); Leaf leaf1 = new Leaf("衬衫"); Leaf leaf2 = new Leaf("夹克"); Leaf leaf3 = new Leaf("裙子"); Leaf leaf4 = new Leaf("套装"); root.addChild(c1); root.addChild(c2); c1.addChild(leaf1); c1.addChild(leaf2); c2.addChild(leaf3); c2.addChild(leaf4); root.printStruct(""); } }
而对于透明模式的话;树枝和树叶类基本不变,就是从接口实现变成了继承实现;
抽象构件;
package compositeClarity; import java.util.List; public abstract class Component { public abstract void printStruct(String preStr); public void addChild(Component child){ throw new UnsupportedOperationException("对象不支持功能"); } public void removeChild(int index){ throw new UnsupportedOperationException("对象不支持功能"); } public List<Component> getChild(){ throw new UnsupportedOperationException("对象不支持功能"); } }
客户端;
package compositeClarity; public class Client { public static void main(String[]args){ Component root = new Composite("服装"); Component c1 = new Composite("男装"); Component c2 = new Composite("女装"); Component leaf1 = new Leaf("衬衫"); Component leaf2 = new Leaf("夹克"); Component leaf3 = new Leaf("裙子"); Component leaf4 = new Leaf("套装"); root.addChild(c1); root.addChild(c2); c1.addChild(leaf1); c1.addChild(leaf2); c2.addChild(leaf3); c2.addChild(leaf4); root.printStruct(""); } }