【设计模式】——组合模式(16)

一、定义

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

二、框架运用

springMVC通过组合模式,使得用户或者说框架本身在进行配置时,就通过操作WebMvcConfigurer类及其衍生类这个整体就行了

三、实战

1、抽象类

public abstract class Component {
    protected String name;

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

    public Component() {
    }

    public abstract void add(Component component);
    public abstract void remove(Component component);
    public abstract void showContent();
}

2、实现类

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

    @Override
    public void add(Component component) {
        System.out.println("叶子节点不能增加下级");

    }

    @Override
    public void remove(Component component) {
        System.out.println("叶子节点不能删除下级");
    }

    @Override
    public void showContent() {
        System.out.println("叶子节点:"+name);
    }
}


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

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

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

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

    @Override
    public void showContent() {
        System.out.println("树干节点:"+name);
        children.forEach(Component::showContent);
    }
}

3、运行和结果

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

        Compsite siteA = new Compsite("树干A");
        Compsite siteB = new Compsite("树干B");
        Compsite siteC = new Compsite("树干C");

        siteA.add(new Leaf("树叶C"));
        siteA.add(new Leaf("树叶D"));
        siteC.add(new Leaf("树叶E"));
        siteC.add(new Leaf("树叶F"));
        siteB.add(siteC);

        root.add(siteA);
        root.add(siteB);

        root.showContent();

        siteB.remove(siteC);

        System.out.println("---------------------分隔符--------------------");

        root.showContent();
    }
}



Connected to the target VM, address: '127.0.0.1:49611', transport: 'socket'
树干节点:根
叶子节点:树叶A
叶子节点:树叶B
树干节点:树干A
叶子节点:树叶C
叶子节点:树叶D
树干节点:树干B
树干节点:树干C
叶子节点:树叶E
叶子节点:树叶F
---------------------分隔符--------------------
树干节点:根
叶子节点:树叶A
叶子节点:树叶B
树干节点:树干A
叶子节点:树叶C
叶子节点:树叶D
树干节点:树干B
Disconnected from the target VM, address: '127.0.0.1:49611', transport: 'socket'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值