个人博客
http://www.milovetingting.cn
组合模式
模式介绍
组合模式也称为部分整体模式,结构型设计模式之一,组合模式比较简单,它将一组相似的对象看作一个对象处理,并根据一个树状结构来组合对象,然后提供一个统一的方法去访问相应的对象,以此忽略对象与对象集合之间的差别。生活中比较经典的例子就是公司的组织结构树状图。
模式定义
将对象组合成树形结构以表示”部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
使用场景
表示对象的部分-整体层次结构时。
从一个整体中能够独立出部分模块或功能时。
简单使用
定义节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public abstract class Component {
protected String name;
public Component(String name) { super(); this.name = name; } public abstract void doSomething(); public abstract void addChild(Component child); public abstract void removeChild(Component child); public abstract Component getChild(int index); }
|
定义枝干节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class Composite extends Component {
private List<Component> components = new ArrayList<>();
public Composite(String name) { super(name); }
@Override public void doSomething() { System.out.println(name); if (components != null) { for (Component c : components) { c.doSomething(); } } }
@Override public void addChild(Component child) { components.add(child); }
@Override public void removeChild(Component child) { components.remove(child); }
@Override public Component getChild(int index) { return components.get(index); }
}
|
定义叶子节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class Leaf extends Component {
public Leaf(String name) { super(name); }
@Override public void doSomething() { System.out.println(name); }
@Override public void addChild(Component child) { throw new UnsupportedOperationException("叶子节点没有子节点"); }
@Override public void removeChild(Component child) { throw new UnsupportedOperationException("叶子节点没有子节点"); }
@Override public Component getChild(int index) { throw new UnsupportedOperationException("叶子节点没有子节点"); }
}
|
调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class Main {
public static void main(String[] args) { Component root = new Composite("Root"); Component branch1 = new Composite("Branch1"); Component branch2 = new Composite("Branch2"); Component leaf1 = new Leaf("Leaf1"); Component leaf2 = new Leaf("Leaf2"); branch1.addChild(leaf1); branch2.addChild(leaf2); root.addChild(branch1); root.addChild(branch2); root.doSomething(); }
}
|
输出结果
1 2 3 4 5
| Root Branch1 Leaf1 Branch2 Leaf2
|