設計模式:組合模式

組合模式(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

相關文章
相關標籤/搜索