温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Composition:组合模式在Java中的实现

发布时间:2025-09-22 18:12:45 来源:亿速云 阅读:106 作者:小樊 栏目:编程语言

组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构来表示“部分-整体”的层次结构。组合模式使得客户端可以统一地处理单个对象和对象的组合。

在Java中,组合模式通常涉及以下几个角色:

  1. Component(抽象构件):为树叶构件和树枝构件声明通用接口,并定义一个接口用于访问和管理它的子部件。
  2. Leaf(叶子构件):表示叶节点对象,叶子节点没有子节点。
  3. Composite(树枝构件):表示分支节点对象,它拥有子节点,可以是叶节点,也可以是另一个树枝节点。

下面是一个简单的Java组合模式实现示例:

Component(抽象构件)

public abstract class Component {
    protected String name;

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

    public void add(Component component) {
        throw new UnsupportedOperationException();
    }

    public void remove(Component component) {
        throw new UnsupportedOperationException();
    }

    public Component getChild(int index) {
        throw new UnsupportedOperationException();
    }

    public abstract void display(int depth);
}

Leaf(叶子构件)

public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void display(int depth) {
        System.out.println("-" + "-".repeat(depth) + name);
    }
}

Composite(树枝构件)

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

public class Composite extends Component {
    private List<Component> children = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

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

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

    @Override
    public Component getChild(int index) {
        return children.get(index);
    }

    @Override
    public void display(int depth) {
        System.out.println("-" + "-".repeat(depth) + name);
        for (Component child : children) {
            child.display(depth + 2);
        }
    }
}

客户端代码

public class Client {
    public static void main(String[] args) {
        // 创建根节点
        Composite root = new Composite("Root");

        // 创建叶子节点
        Leaf leaf1 = new Leaf("Leaf 1");
        Leaf leaf2 = new Leaf("Leaf 2");

        // 创建树枝节点
        Composite branch1 = new Composite("Branch 1");
        Leaf leaf3 = new Leaf("Leaf 3");
        Leaf leaf4 = new Leaf("Leaf 4");

        // 构建树形结构
        root.add(branch1);
        root.add(leaf1);
        root.add(leaf2);

        branch1.add(leaf3);
        branch1.add(leaf4);

        // 显示树形结构
        root.display(0);
    }
}

在这个示例中,Component 是抽象构件,Leaf 是叶子构件,Composite 是树枝构件。客户端代码创建了一个树形结构并显示它。组合模式使得客户端可以统一地处理单个对象和对象的组合,而不需要关心它们的具体类型。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI