定义:

    Compose objects into tree structures to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of objects uniformly.(将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。) 设计模式之禅 第2版

    我的理解是,模拟树状结构.感觉这个应用在数据库中更好

    组合模式由三个角色组成:

    • Component:抽象出leaf,composite的共有方法与属性
    • Leaf:叶子,其下再也没有其他分支
    • Composite:树枝,有父节点与子节点

    类图如下:

    组合模式 - 图1

    代码:

    Composite:

    • 存储Leaf,这个根据线程环境,Composite下的Leaf估算数量来选择合适的数据结构
    • 实现对Leaf的CRUD
    1. public class Composite extends Component {
    2. private ArrayList<Component> componentArrayList = new ArrayList<Component>();
    3. @Override
    4. public void doSomething() {
    5. super.doSomething();
    6. }
    7. public void add(Component component){
    8. this.componentArrayList.add(component);
    9. }
    10. public void remove(Component component){
    11. this.componentArrayList.remove(component);
    12. }
    13. public ArrayList<Component> getChildren(){
    14. return this.componentArrayList;
    15. }
    16. }

    Leaf: 重写需要Component的行为就好

    1. public class Leaf extends Component {
    2. @Override
    3. public void doSomething() {
    4. super.doSomething();
    5. }
    6. }

    Component

    1. public class Component {
    2. public void doSomething(){};
    3. }

    以上是组合模式的安全模式,还有一种透明模式.就是将对子节点的CRUD抽象到Component中,对于可以有子节点的Composite,无所谓,但对于不可以有子节点的Leaf,需要进行重写,避免其使用.这里可以用@Deprecated提醒调用方法,加上调用就抛出UnsupportedOperationException异常来规避调用CRUD的风险