大话设计模式-组合模式

UML

根节点

/** * 根节点 */
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 getDepth(int depth) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            stringBuilder.append('-');
        }
        return stringBuilder.toString();
    }

}

叶子节点

/** * 叶子节点 */
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 disPlay(int depth) {
        System.out.println(getDepth(depth) + name);
    }
}

枝节点

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

/** * 枝节点 */
public class Composite extends Component {
    private List<Component> tree = new ArrayList<>();

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

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

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

    @Override
    public void disPlay(int depth) {
        System.out.println(getDepth(depth) + name);
        for (Component component : tree) {
            component.disPlay(depth + 2);
        }
    }


}

测试类

/** * 测试类 */
public class Main {
    public static void main(String[] args) {
        Component root = new Composite("Root");
        root.add(new Leaf("叶子—1"));
        root.add(new Leaf("叶子—2"));
        root.add(new Leaf("叶子—3"));

        Component component = new Composite("树枝—1");
        component.add(new Leaf("叶子—1"));
        component.add(new Leaf("叶子—2"));
        component.add(new Leaf("叶子—3"));

        Composite composite = new Composite("树枝—1—1");
        composite.add(new Leaf("叶子—1"));
        composite.add(new Leaf("叶子—2"));
        composite.add(new Leaf("叶子—3"));
        component.add(composite);

        root.add(component);
        root.disPlay(1);

    }
}

输出结果

全部评论

相关推荐

像好涩一样好学:这公司我也拿过 基本明确周六加班 工资还凑活 另外下次镜头往上点儿
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务