Java设计模式——结构性模式——组合模式(COMPSITE)
组合模式,又称为 部分整体模式,把具有相似的一组对象 当做一个对象处理,用一种树状的结构来组合对象,再提供统一
---file B
---file1
-----file C
的方法去访问相似的对象,以此忽略掉对象与对象容器间的差别。
组合模式允许你将对象组合成树形结构来表现”部分-整体“的层次结构,使得客户以一致的方式处理单个对象以及对象的组合。
组合模式实现的最关键的地方是——简单对象和复合对象必须实现相同的接口。这就是组合模式能够将组合对象和简单对象进行一致处理的原因。
- 组合部件(Component):它是一个抽象角色,为要组合的对象提供统一的接口。
- 叶子(Leaf):在组合中表示子节点对象,叶子节点不能有子节点。
- 合成部件(Composite):定义有枝节点的行为,用来存储部件,实现在Component接口中的有关操作,如增加(Add)和删除(Remove)。
-
package sheji; /** * Created with IntelliJ IDEA. * User:by gyw * Date:2018-04-05 14:14 */ public abstract class Component { //节点 protected String name; //内容 public Component(String name){ this.name=name; } public Component(){ } public abstract void add(Component component); //添加 public abstract void remove(Component component); //删除 public abstract void display(int depth); //展示 public String getName() { return name; } public void setName(String name) { this.name = name; } }
package sheji; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User:by gyw * Date:2018-04-05 14:17 *枝节点类 */ public class ConcreteCompany extends Component{ private List<Component> list; public ConcreteCompany(String name) { super(name); list=new ArrayList<Component>(); } public ConcreteCompany(){ list=new ArrayList<Component>(); } @Override public void add(Component component) { list.add(component); } @Override public void remove(Component component) { list.remove(component); } @Override public void display(int depth) { StringBuilder sb = new StringBuilder(""); for (int i = 0; i < depth; i++) { sb.append("-"); } System.out.println(new String(sb) + this.getName()); for (Component c : list) { c.display(depth + 2); } } }
package sheji; /** * Created with IntelliJ IDEA. * User:by gyw * Date:2018-04-05 14:18 * 叶子节点 */ public class Leaf extends Component{ public Leaf(String name){ super(name); } @Override public void add(Component component) { // TODO Auto-generated method stub } @Override public void remove(Component component) { // TODO Auto-generated method stub } @Override public void display(int depth) { StringBuilder sb = new StringBuilder(""); for (int i = 0; i < depth; i++) { sb.append("-"); } System.out.println(new String(sb) + this.getName()); } }
package sheji; /** * Created with IntelliJ IDEA. * User:by gyw * Date:2018-04-05 14:19 */ public class Client { public static void main(String[] args) { Component root=new ConcreteCompany("root"); root.add(new Leaf("file A")); root.add(new Leaf("file B")); Component file=new ConcreteCompany("file1"); file.add(new Leaf("file C")); file.add(new Leaf("file D")); root.add(file); root.display(1); } }
测试结果
-root
---file A---file B
---file1
-----file C
-----file D
组合模式适用场景
1.你想表示对象的部分-整体层次结构
2.你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。