十五 设计模式之组合模式
2011-01-25 09:15
253 查看
定义
将对象组合成树形结构以表示“部分
-
整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性
类图
通用代码
优点
1.
高层模块调用简单
高层模块不必关心自己处理的是单个对象还是整个组合结构
2.
节点自由增加
缺点
场景类中,树枝和树叶使用时都需用起实现类,与依赖倒置原则冲突,没有面向接口编程
使用场景
1.
维护和展示部分
-
整体关系的场景,如树形菜单,文件和文件夹管理
2.
从一个整体中能够独立出部分模块或功能的场景
只要是树形结构就可以考虑使用组合模式
将对象组合成树形结构以表示“部分
-
整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性
类图
通用代码
//抽象构件 public abstract class Component { //个体和整体都具有的共享 public void operation(){ //doSomething } } //树枝构件 public class Composite extends Component { private ArrayList<Component> componentArrayList = new ArrayList<Component>(); public void Add(Component param) { this.componentArrayList.add(param); } public void Remove(Component param) { this.componentArrayList.remove(param); } public ArrayList<Component> GetChild() { return this.componentArrayList; } } //树叶构件 public class Leaf extends Component { } //场景类 public class Client { public static void main(String args[]){ //创建一个根节点 Composite root = new Composite(); root.operation(); Composite branch = new Composite(); Leaf leaf = new Leaf(); root.Add(branch); root.Add(leaf); } public static void display(Composite root){ for(Component c:root.GetChild()){ if(c instanceof Leaf){ c.operation(); }else{ display((Composite)c); } } } }
优点
1.
高层模块调用简单
高层模块不必关心自己处理的是单个对象还是整个组合结构
2.
节点自由增加
缺点
场景类中,树枝和树叶使用时都需用起实现类,与依赖倒置原则冲突,没有面向接口编程
使用场景
1.
维护和展示部分
-
整体关系的场景,如树形菜单,文件和文件夹管理
2.
从一个整体中能够独立出部分模块或功能的场景
只要是树形结构就可以考虑使用组合模式
相关文章推荐
- 设计模式之十五:组合模式(Composite)
- 步步为营 .NET 设计模式学习笔记 十五、Composite(组合模式)
- 步步为营 .NET 设计模式学习笔记 十五、Composite(组合模式)
- 设计模式C++实现十五:组合模式
- 设计模式实现(十五)--- 组合模式(Composite)
- 设计模式—组合模式(十五)
- 设计模式学习笔记(十五:组合模式)
- 十五、组合模式——设计模式学习笔记
- 步步为营 .NET 设计模式学习笔记 十五、Composite(组合模式)
- Java设计模式(五)Facade(外观),Composite(组合),Decorator(油漆工)
- 设计模式---复合模式(策略-适配器-装饰者-抽象工厂-组合-观察者)
- 设计模式—组合模式
- 设计模式之Composite(组合)
- GOF 23设计模式之 组合模式(composite)
- 设计模式(七)组合模式Composite(结构型)
- IOS设计模式之组合设计模式
- 23种设计模式之十五(行为模式)State模式
- 设计模式——组合模式+案例
- Java设计模式十五:备忘录模式(Memento)
- Java设计模式--组合模式