组合模式
2016-05-14 19:11
357 查看
组合模式的定义:
主要用来描述部分和整体的关系,其定义如下:
Compose objects into tree structure to represent part-whole hierarchies. Composite lets clients treat
individual objects and compositions of objects uniformly.
将对象组合成树形结构以表示“部分——整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
组合模式的角色:
1.Component抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性
2.Leaf叶子构件
叶子对象,其下面也没有其他分支,也就是遍历的最小单位
3.Composite树枝构件
树枝对象,它的作用是组合树枝节点或叶子节点形成一个树形结构
主要用来描述部分和整体的关系,其定义如下:
Compose objects into tree structure to represent part-whole hierarchies. Composite lets clients treat
individual objects and compositions of objects uniformly.
将对象组合成树形结构以表示“部分——整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
组合模式的角色:
1.Component抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性
2.Leaf叶子构件
叶子对象,其下面也没有其他分支,也就是遍历的最小单位
3.Composite树枝构件
树枝对象,它的作用是组合树枝节点或叶子节点形成一个树形结构
//抽象构件 public abstract class Component{ public void doSomething(){ // } } //树枝构件 public class Composite extends Component{ private ArrayList<Component> componentArrayList=new ArrayList<Component>(); public void add(Component component){ this.componentArrayList.add(component); } public void remove(Component component){ this.componentArrayList.remove(component); } public ArrayList<Component> getChildren(){ return this.componentArrayList; } } //树叶构件 public class Leaf extends Component{ /* *可以覆盖父类方法 public void doSomething(){ } */ } //场景类 public class Client{ public static void main(String[] args){ //创建一个根节点 Composite root=new Composite(); root.doSomething(); //构建一个树形节点 Composite branch=new Composite(); Leaf leaf=new Leaf(); //建立整体 root.add(branch); branch.add(leaf); } //通过递归遍历树 public static void display(Composite root){ for(Component c:root.getChildren()){ if(c instanceof Leaf){//叶子节点 c.doSomething(); }else{//树枝节点 display((Composite)c); } } } }
相关文章推荐
- java基础学习总结六(对象与类、类的属性与方法)
- Android(java)学习笔记207:Android下的属性动画(Property Animation)
- 2016百度之星资格赛1001
- 使用design.widget.TabLayout
- 第十一周进度条
- 语法分析(6)...
- L3-2 堆栈 团体程序设计天梯赛-练习集
- ElasticSearch(四)--分布式文档存储
- 基于SSH框架开发的《高校大学生选课系统》的质量属性的实现
- 如何利用hibernate3解决数据库丢失更新问题?
- JVM监控工具介绍
- PHP笔记②所有输出语句
- ORA-03113
- 仿美团外卖,饿了吗 两个ListView联动,左边点击切换右边,右边滑动切换左边
- RMQ (范 围 最 值 问 题)
- 第17章 KDE的Qt
- java反射机制
- 关于三年工作的一点点感悟
- 5-38 数列求和-加强版 (20分)
- linux驱动模板