设计模式之组合模式

组合模式

组合模式分为安全组合模式和透明组合模式,本文下的示例代码为透明组合模式,在叶子节点中冗余实现了叶子节点不需要的方法,而安全组合模式则需要进行叶子节点和普通节点的区分.

  1. 组合模式结构图

  2. 示例代码

// 抽象类
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 class Leaf extends Component{

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

    @Override
    public void add(Component component) {

    }

    @Override
    public void remove(Component component) {

    }

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

// 普通节点
public class Composite extends Component{

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

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

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

    @Override
    public void display(int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("-");
        }
        System.out.println(name);
        for (Component component : list) {
            component.display(depth + 2);
        }
    }
}

// 测试
public class CompositeTest {

    public static void main(String[] args) {
        Component root = new Composite("root");
        Component branch1 = new Composite("branch1");
        Component branch2 = new Composite("branch2");
        Component leaf1 = new Composite("leaf1");
        Component branch11 = new Composite("branch11");
        Component branch12 = new Composite("branch12");
        Component branch13 = new Composite("branch13");
        Component leaf21 = new Composite("leaf21");
        Component leaf121 = new Composite("leaf121");
        root.add(branch1);
        root.add(branch2);
        root.add(leaf1);
        branch1.add(branch11);
        branch1.add(branch12);
        branch1.add(branch13);
        branch12.add(leaf121);
        branch2.add(leaf21);

        root.display(2);
    }
}

  1. 总结:

    优点:清楚的定义了各层次的复杂对象,符合开闭原则;

    缺点:限制类型时会较为复杂,使设计变得更加抽象.

posted @ 2021-04-17 13:47  justKen  阅读(58)  评论(0编辑  收藏  举报