设计模式——组合模式原理及代码实现

一、简介

组合模式(Composite Pattern),将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

在对象关系之间存在上下层级结构时使用,可以忽略组合对象和单个对象的不同,统一地使用组合结构中的所有对象。

基本对象可以被组合成更复杂的组合对象,而这个组合对象又可以被组合,这样就可以递归下去。

二、结构图

Component:组合中的对象声明接口,在适当情况下,实现所有类公共接口的默认行为。声明一个接口用于访问和管理Component的子部件。

Leaf:在组合中表示叶节点对象,叶节点没有子节点。

Composite:定义有枝节点行为,用于存储子部件,在Component中实现与子部件有关的操作,比如增加、删除。

三、代码实现

1.Component

public abstract class Component {
    protected String name;

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

    public abstract void add(Component component);
    public abstract void remove(Component component);
    public abstract void display(int depth);

    public String getSpace(int depth) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            stringBuilder.append("-");
        }
        return stringBuilder.toString();
    }
}

 2.Leaf

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

    @Override
    public void add(Component component) {
        System.out.println("can not add to a leaf");
    }

    @Override
    public void remove(Component component) {
        System.out.println("can not remove a leaf");
    }

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

3.Composite

public class Composite extends Component{
    private List<Component> components = new ArrayList<>();
    public Composite(String name) {
        super(name);
    }

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

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

    @Override
    public void display(int depth) {
        System.out.println(getSpace(depth) + name);
        components.stream().forEach(component -> component.display(depth + 1));
    }
}

4.Client:测试类

public class Client {
    public static void main(String[] args) {
        Composite root = new Composite("root");
        root.add(new Leaf("A"));
        root.add(new Leaf("B"));

        Composite comp = new Composite("X");
        comp.add(new Leaf("Leaf XA"));
        comp.add(new Leaf("Leaf XB"));

        Composite comp2 = new Composite("Y");
        comp2.add(new Leaf("Leaf YA"));
        comp2.add(new Leaf("Leaf YB"));

        comp.add(comp2);
        root.add(comp);

        root.display(1);
    }
}

5.测试结果

-root
--A
--B
--X
---Leaf XA
---Leaf XB
---Y
----Leaf YA
----Leaf YB

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值