设计模式:组合模式

组合模式(Composite):是结构型模式的一种,它是一种组合拆分可重复使用的数型结构.java

分支于接点依赖于同一个抽象(实现/继承 于同一 接口/类).啥都别说了,上图ide

package com.fumeck.design.composite;

/**
 * 组件接口
 */
public interface Component {
    void add(Component component);
    void remove(Component component);
    void excute(int depth);


    /**
     *
     * @param number
     * @return
     * 格式化字符串,左对齐
     */
     static String lpad(int number)
    {
        String f = "";
        for (int i = 0; i < number; i++) {
            f+="-";
        }
        return f;
    }
}
package com.fumeck.design.composite;

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

/**
 * 枝节点
 */
public class Composite implements Component {
    private String name;

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

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

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

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

    @Override
    public void excute(int depth) {
        System.out.println(Component.lpad(depth)+name);
        for (Component c : cs) {
            c.excute(depth + depth);
        }
    }

}
package com.fumeck.design.composite;

/**
 * 叶节点
 */
public class Leaf implements Component {
    private String name;

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

    @Override
    public void add(Component component) {

    }

    @Override
    public void remove(Component component) {

    }

    @Override
    public void excute(int depth) {
        System.out.println(Component.lpad(depth)+name);
    }

}
package com.fumeck.design.composite;

public class Client {
    public static void main(String[] args) {
        Component root = new Composite("根部门");
        //第二层-部门及其下小组
        Component second = new Composite("二层部门");
        second.add(new Leaf("secondLeaf1"));
        second.add(new Leaf("secondLeaf2"));
        root.add(second);
        //第二层-小组
        Component second_2 = new Leaf("二层小组");
        root.add(second_2);
        //第二层-部门的部门等
        Component second_3 = new Composite("二层部门2");
        Component thrid = new Composite("三层部门子部门");
        thrid.add(new Leaf("thridLeaf1"));
        thrid.add(new Leaf("thridLeaf2"));
        second_3.add(thrid);
        root.add(second_3);
        root.excute(2);
    }
}

控制台console:this

--根部门
----二层部门
--------secondLeaf1
--------secondLeaf2
----二层小组
----二层部门2
--------三层部门子部门
----------------thridLeaf1
----------------thridLeaf2code

相关文章
相关标签/搜索