设计模式之组合模式(Composite)

概述

是一种结构型模式,将对象以树形结构组织起来,以表示“部分 - 整体”的层次结构,使得客户端对单个对象和组合对象的使用具有唯一性。

UML类图
这里写图片描述

上面的类图包含的角色:
Component:为参加组合的对象声明一个公共的接口,不管是组合还是叶节点。
Leaf:在组合中表示叶子结点对象,叶子结点没有子结点。
Composite:表示参加组合的有子对象的对象,并给出树枝构建的行为;

代码示例

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

abstract class Component {

    protected String name;

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

    public abstract void Add(Component c);

    public abstract void Remove(Component c);

    public abstract void GetChild(int depth);
}

class Leaf extends Component {

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

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

    @Override
    public void Remove(Component c) {
        System.out.println("Can not remove from a leaf");
    }

    @Override
    public void GetChild(int depth) {
        String temp = " ";
        for (int i = 0; i < depth; i++) {
            temp += "-";
            System.out.println(temp + name);
        }
    }

}

class Composite extends Component {

    private List<Component> children = new ArrayList<>();

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

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

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

    @Override
    public void GetChild(int depth) {

        for (Component c : children) {
            c.GetChild(depth);
        }
    }

}

public class Main {

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

        Composite compX = new Composite("Composite X");
        compX.Add(new Leaf("Leaf XA"));
        compX.Add(new Leaf("Leaf XB"));
        root.Add(compX);

        Composite compXY = new Composite("Composite XY");
        compXY.Add(new Leaf("Leaf XYA"));
        compXY.Add(new Leaf("Leaf XYB"));
        compX.Add(compXY);

        root.GetChild(3);
    }

}

应用场景

1.要求表示对象的部分-整体层次结构。
2.想要客户端忽略组合对象与单个对象的差异,客户端将统一地使用组合结构中的所有对象。

组合模式定义由Leaf对象和Composite对象组成的类结构;
使得客户端变得简单;
它使得添加或删除子部件变得很容易。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值