10.15

组合模式

下面是一个简单的Java代码示例,展示了组合模式的现实:

import java.util.ArrayList;
import java.util.List;

// 组件抽象类
abstract class Component {
    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public abstract void operation();
}

// 叶子节点类
class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void operation() {
        System.out.println("Leaf " + name + " operation");
    }
}

// 容器节点类
class Composite extends Component {
    private List<Component> children;

    public Composite(String name) {
        super(name);
        children = new ArrayList<>();
    }

    public void add(Component component) {
        children.add(component);
    }

    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public void operation() {
        System.out.println("Composite " + name + " operation");
        for (Component component : children) {
            component.operation();
        }
    }
}

// 客户端代码
public class CompositePatternExample {
    public static void main(String[] args) {
        // 创建树形结构
        Composite root = new Composite("root");
        Composite branch1 = new Composite("branch1");
        Composite branch2 = new Composite("branch2");
        Leaf leaf1 = new Leaf("leaf1");
        Leaf leaf2 = new Leaf("leaf2");
        Leaf leaf3 = new Leaf("leaf3");

        root.add(branch1);
        root.add(branch2);
        branch1.add(leaf1);
        branch2.add(leaf2);
        branch2.add(leaf3);

        // 调用操作方法
        root.operation();
    }
}

在上面的示例中,我们确定了一个抽象类Component,它包含一个名为operation()的抽象方法,该方法用于执行组件的操作。

然后,我们实际上发现了叶子节点类Leaf和容器点类Composite。叶子节点类显示组合中的叶子对象,容器点类显示组合中的容器对象。容器节点类内部维护了一个子组列表,并提供了添加、删除子组的方法。

在客户端代码中,我们创建了一个树形结构,包括根节点、分支节点和叶子节点,并进行了组件的添加和连接。最后。 ,我们调整使用根节点的方法,触发整个组合结构的操作operation()

组合模型的关键思想是将对象组合成树形结构以表示“整体-部分”的层次结构,使用户对单个象和组合合对象的使用工具有一个致性。通过组合模式,我们可以用统一的方式处理组合结构中的叶子节点和容器节点,使客户终端代码更加简洁和灵活。

posted @   liuxuechao  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示