设计模式:组合模式

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

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

212219_4lVq_2283248.png

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:

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

转载于:https://my.oschina.net/u/2283248/blog/1832403

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值