对象结构型模式——组合模式(Composite Pattern)
来源:互联网 发布:雅尔塔体系 知乎 编辑:程序博客网 时间:2024/05/21 15:43
- 定义
组合模式将对象组合成整体-部分的层次结构,使得整体和部分的处理具有一致性。 - 概述
组合模式使用一个抽象类,使得叶节点和枝节点能够统一起来,用户可以不再区分就可以对枝和叶做统一处理。
component(抽象组件):为组合的对象声明接口,使用户可以统一的访问和管理组合对象,这里可以实现缺省功能。
leaf(叶节点):定义和实现叶节点的功能
composite(枝节点):定义和实现枝节点的功能
这样,枝和叶就分开了,并且都继承自抽象组件,具有统一性 - 实例(Java 语言)
抽象组件
public abstract class Component { /** * Some operation.子组件可能有的功能 */ public abstract void someOperation(); public void addChild(Component component){ new UnsupportedOperationException(); } public void removeChild(Component component){ new UnsupportedOperationException(); } public Component getChild(int i) { throw new UnsupportedOperationException(); }}
枝节点
public class Composite extends Component { private ArrayList<Component> list = null; @Override public void someOperation() { if (list!=null) { for (Component c:list) { c.someOperation(); } } } @Override public void addChild(Component component) { if (list ==null) { list = new ArrayList<>(); } list.add(component); } @Override public void removeChild(Component component) { if (list!=null) { list.remove(component); } } @Override public Component getChild(int i) { if (list!=null) { if (i>=0&&i<list.size()) { return list.get(i); } } return null; }}
叶节点
public class Leaf extends Component { @Override public void someOperation() { System.out.println("打印信息。。。"); }}
测试及结果
public class HeadFirstTest { public static void main(String[] args) { Composite root = new Composite(); Composite a1 = new Composite(); Composite a2 = new Composite(); Leaf leaf1 = new Leaf(); Leaf leaf2 = new Leaf(); Leaf leaf3 = new Leaf(); Leaf leaf4 = new Leaf(); root.addChild(a1); root.addChild(a2); root.addChild(leaf1); a1.addChild(leaf2); a2.addChild(leaf3); a2.addChild(leaf4); Component child1 = root.getChild(1); child1.someOperation(); }}结果打印信息。。。打印信息。。。Process finished with exit code 0
- 类图
如有错误,请留言更正,或进580725421群讨论,以免误导其他开发者!!!
阅读全文
0 0
- 对象结构型模式——组合模式(Composite Pattern)
- 组合模式(Composite Pattern,对象结构型模式)
- 结构型模式:组合模式(Composite Pattern)
- 【设计模式】结构型模式——组合模式(Composite Pattern)
- 对象结构型——组合模式(Composite)
- 设计模式(结构型)之组合模式(Composite Pattern)
- 结构型设计模式之组合模式(Composite Pattern)
- Composite 组合对象结构型模式
- 组合模式-Composite Pattern
- Composite Pattern(组合模式)
- 【组合模式】Composite Pattern
- 组合模式 Composite Pattern
- 组合模式(Composite Pattern)
- 组合模式(Composite Pattern)
- 组合模式【Composite Pattern】
- 组合模式(Composite Pattern)
- composite pattern -- 组合模式
- 组合模式(Composite Pattern)
- java.util.concurrent.Executors
- Eclipse编码方式
- mmap映射详解
- 数据抓取分析(python + mongodb)Python数据抓取分析
- Win10下虚拟机VmwareWorkstation12安装CentOS7系统64位ip设置
- 对象结构型模式——组合模式(Composite Pattern)
- NOIP模拟(10.24)T3 Math
- 安卓--黑域
- OkHttpUtils
- lua 中的#和table.getn
- Android学习资源
- IDEA隐藏.iml等自动生成文件
- ios CocoaPods 的使用教程
- 线段树区间/杂谈