本文共 2266 字,大约阅读时间需要 7 分钟。
在现实生活中,存在很多“部分-整体”的关系,例如,大学中的部门与学院、总公司中的部门与分公司、学习用品中的书与书包、生活用品中的衣服与衣柜、以及厨房中的锅碗瓢盆等。在软件开发中也是这样,例如,文件系统中的文件与文件夹、窗体程序中的简单控件与容器控件等。对这些简单对象与复合对象的处理,如果用组合模式来实现会很方便。
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
这种模式创建了一个包含自己对象组的类。该类提供了修改相同对象组的方式。
组合模式包含以下主要角色。
定义抽象构件:
package com.siyi.compositepattern;public interface Component { public void operation();}
定义树叶构件:
package com.siyi.compositepattern;//树叶构件public class Leaf implements Component { String name; public Leaf(String name) { this.name = name; } @Override public void operation() { System.out.println(name); }}
定义树枝构建:
package com.siyi.compositepattern;import java.util.ArrayList;//树枝构件public class Composite implements Component { String name; ArrayListchildren = new ArrayList (); public Composite(String name){ this.name = name; } public void add(Component c) { children.add(c); } public void remove(Component c) { children.remove(c); } public Component getChild(int i) { return children.get(i); } @Override public void operation() { System.out.println(name); }}
Main方法:
package com.siyi.compositepattern;public class Main { public static void main(String[] args) { Composite root = new Composite("root"); Composite c = new Composite("c"); Component leaf1 = new Leaf("1"); Component leaf2 = new Leaf("2"); Component leaf3 = new Leaf("3"); root.add(c); root.add(leaf1); c.add(leaf2); c.add(leaf3); tree(root,0); } public static void tree(Component c, int depth) { for(int i=0; i
运行结果:
root--c----2----3--1
优点:
缺点:
转载地址:http://oryof.baihongyu.com/