十六、组合模式 Composite
2017-03-29 17:24
369 查看
一、定义
组合模式:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象个组合对象的使用具有一致性。应用:当你发现需求中是体现部分与真题层次的结构是,以及你希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,就应该考虑使用组件设计模式。
二、结构图
三、代码示例
/** * @use 测试组合模式 * @author lattice * @date 2017-01-03 */ public class CompositeTest { public static void main(String[] args) { Composite root=new Composite("root"); root.add(new Leaf("leaf A")); Composite comp=new Composite("composite A"); comp.add(new Leaf("leaf A of composite A")); comp.add(new Leaf("leaf B of composite A")); root.add(comp); root.add(new Leaf("leaf B")); root.display(1); /** * 输出结果 * -root ---leaf A ---composite A -----leaf A of composite A -----leaf B of composite A ---leaf B */ } } abstract class Component { protected String name; public Component(String name) { this.name = name; } public String getString(String str, int number) { String result = ""; for (int i = 0; i < number; i++) { result += str; } return result; } public abstract void add(Component c); public abstract void remove(Component c); public abstract void display(int depth); } class Leaf extends Component { public Leaf(String name) { super(name); } public void add(Component c) { System.out.println("connot add to a leaf"); } public void remove(Component c) { System.out.println("connot remove from a leaf"); } public void display(int depth) { System.out.println(getString("-", depth) + name); } } class Composite extends Component { private ArrayList<Component> childrens = new ArrayList<Component>(); public Composite(String name) { super(name); } public void add(Component c) { childrens.add(c); } public void remove(Component c) { childrens.remove(c); } public void display(int depth) { System.out.println(getString("-", depth) + name); for(Component sb:childrens){ sb.display(depth+2); } } }
相关文章推荐
- Java设计模式十六:组合模式(Composite Pattern)
- 设计模式之Composite(组合)
- 设计模式(10)-组合模式(Composite)
- .NET实用设计模式:组合模式(Composite)
- 设计模式之Composite(组合)
- 窥视设计模式之组合模式(composite)
- 在组合(Composite)模式中实现访问者(Visitor)模式
- C#面向对象设计模式纵横谈 学习笔记9 Composite 组合(结构型模式)
- 设计模式之Composite(组合)
- 结构模式——设计模式之Composite(组合)[转载自http://www.jdon.com/]
- Composite 组合模式(结构型模式)
- 《设计模式》学习笔记--组合模式Composite
- 设计模式(8)-组合模式(Composite)
- java设计模式之Composite(组合) (转)
- 组合模式(Composite)
- 设计模式袖珍版 连续转载之 - Composite(组合)
- C#设计模式之组合(Composite)
- 窥视设计模式之组合模式(composite)
- 设计模式 --- 组合模式(Composite) 精选经验合集
- 组合模式(composite)学习