设计模式之Composite模式(笔记)
2016-03-31 18:12
337 查看
组合模式:将对象组合成树形结构以表示“部分-总体”的层次结构。
组合模式使得用户对单个对象和组合对象的使用具有一致性。
适用场合:当需求中是体现部分与总体层次的结构时,以及希望用户能够忽略组合对象与单个对象的不同,统一地使用组合结构中的全部对象时,就应该考虑用组合模式。
首先定义一个Componet抽象类
定义叶结点对象Leaf,继承Componet
结点定义枝结点Composite继承Component
client代码
结果:
-root
- - -LeafA
- - -LeafB
- - -Composite X
- - - - -LeafXA
- - - - -LeafXB
- - -Composite Y
- - - - -LeafXYA
- - - - -LeafXYB
- - -LeafC
组合模式使得用户对单个对象和组合对象的使用具有一致性。
适用场合:当需求中是体现部分与总体层次的结构时,以及希望用户能够忽略组合对象与单个对象的不同,统一地使用组合结构中的全部对象时,就应该考虑用组合模式。
首先定义一个Componet抽象类
public abstract class Component { protected String name; public Component(String name){ this.name=name; } //抽象方法 public abstract void add(Component c); public abstract void delete(Component c); public abstract void dispaly(int depth); }
定义叶结点对象Leaf,继承Componet
public class Leaf extends Component { public Leaf(String name) { super(name); } @Override public void add(Component c) { System.out.println("can not add a leaf"); } @Override public void delete(Component c) { System.out.println("can not delete a leaf"); } @Override public void dispaly(int depth) { char[] ch=new char[depth]; for(int i=0;i<depth;i++){ ch[i]='-'; } System.out.println(new String(ch)+name); } }
结点定义枝结点Composite继承Component
public class Composite extends Component{ private List<Component> children=new ArrayList<Component>(); public Composite(String name) { super(name); } @Override public void add(Component c) { children.add(c); } @Override public void delete(Component c) { children.remove(c); } @Override public void dispaly(int depth) { char[] ch=new char[depth]; for(int i=0;i<depth;i++){ ch[i]='-'; } System.out.println(new String(ch)+name); Iterator<Component> iterator=children.iterator(); while(iterator.hasNext()){ Component component=iterator.next(); component.dispaly(depth+2); } } }
client代码
public static void main(String[] args) { //组合模式 Composite root=new Composite("root"); root.add(new Leaf("LeafA")); root.add(new Leaf("LeafB")); Composite comp=new Composite("Composite X"); comp.add(new Leaf("LeafXA")); comp.add(new Leaf("LeafXB")); root.add(comp); Composite comp2=new Composite("Composite Y"); comp2.add(new Leaf("LeafXYA")); comp2.add(new Leaf("LeafXYB")); root.add(comp2); root.add(new Leaf("LeafC")); root.dispaly(1); }
结果:
-root
- - -LeafA
- - -LeafB
- - -Composite X
- - - - -LeafXA
- - - - -LeafXB
- - -Composite Y
- - - - -LeafXYA
- - - - -LeafXYB
- - -LeafC
相关文章推荐
- Nginx反向代理配置文件
- s:textarea 标签不能改变大小的解决方案
- Java设计模式之代理模式
- Posix消息队列
- css实现自适应屏幕高度
- Boost中的单利模式
- python基础练习(一)——自定义函数,数学运算,命令行输入
- JS中Date对象getYear()方法和getFullYear()方法区别
- 关于混淆矩阵的元素排序问题
- ListView和GridView实现单选效果
- Eclipse中SVN如何切换分支
- ORMLite的几个关键注解的使用说明
- Logstash分析MySQL慢查询日志
- java学习一:基本数据类型
- ubuntu开发环境部署流程
- IOS 获取当前版本信息
- DJango框架对Models操作
- 让任意线程执行一个匿名函数
- 修改ibdata1大小的验证以及如何使用mysqld_multi管理多实例
- 执行环境和作用域链