【设计模式】组合模式

类图

【设计模式】组合模式

工程目录

【设计模式】组合模式

代码

AbstractComponent.java

package com.company.pattern.demo15;

/**
 * 声明组合中的对象的接口,在适当的情况下,实现所有类共有接口的默认行为
 * @author blazar
 */
public abstract class AbstractComponent {
    protected String name;

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

    /**
     * 添加组件
     * @param c
     */
    public abstract void add(AbstractComponent c);

    /**
     * 移除组件
     * @param c
     */
    public abstract void remove(AbstractComponent c);

    /**
     * 显示节点的名称,并对其下级进行遍历
     * @param depth
     */
    public abstract void display(int depth);
}

Composite.java

package com.company.pattern.demo15;

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

/**
 * @author balzar
 */
public class Composite extends AbstractComponent{

    /**
     * 子对象集合,用来存储其下属的非叶子节点和叶子节点
     */
    private List<AbstractComponent> children = new ArrayList<>();

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

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

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

    @Override
    public void display(int depth) {
        System.out.println(String.join("", Collections.nCopies(depth, "-")) + " " + name);

        for(AbstractComponent abstractComponent : children){
            abstractComponent.display(depth+1);
        }
    }
}

Leaf.java

package com.company.pattern.demo15;

import java.util.Collections;

/**
 * Leaf在组合中表示叶节点对象,叶节点没有子节点
 * @author blazar
 */
public class Leaf extends AbstractComponent{
    public Leaf(String name){
        super(name);
    }

    @Override
    public void add(AbstractComponent c) {
        System.out.println("Cannot add to a leaf");
    }

    @Override
    public void remove(AbstractComponent c) {
        System.out.println("Cannot remove from a leaf");
    }

    @Override
    public void display(int depth) {
        System.out.println(String.join("", Collections.nCopies(depth, "-")) + " " + name);
    }
}

测试类 Main.java

package com.company.pattern.demo15;

/**
 * 测试类
 * @author blazar
 */
public class Main {
    public static void main(String[] args) {
        AbstractComponent root = new Composite("root");
        root.add(new Leaf("Leaf A"));
        root.add(new Leaf("Leaf B"));

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

        root.add(component);

        AbstractComponent composite2 = new Composite("Composite XY");
        composite2.add(new Leaf("Leaf XYA"));
        composite2.add(new Leaf("Leaf XYB"));

        component.add(composite2);

        root.display(1);
    }
}

参考《大话设计模式》

上一篇:CF1103C Johnny Solving(构造题)


下一篇:LeetCode题解:897. 递增顺序搜索树,栈,JavaScript,详细注释