当前位置:   article > 正文

设计模式-组合模式Composite(结构型)

设计模式-组合模式Composite(结构型)

组合模式(Composite)

组合模式是一种结构型模式,它可以将对象组合成树状结构,用来区分部分和整体的层次机构,又叫部分整体模式

角色

  1. 组件:组合中所有对象的通用接口,可以是抽象类或者接口,声明管理子组件的方法,通常包括新增、删除、获取等方法
  2. 叶子节点:表示组合叶子节点对象,它没有子节点,实现组件的方法,但不包括子组件
  3. 复合节点:表示组件中的符合对象,实现组件方法,它可以包含子组件,也可是叶子节点
  4. 客户端:通过组合接口与组合结构交互,不区分叶子节点和复合节点,可以一致的对待整体与部分

案例

将书作为叶子节点,将目录作为符合节点


public interface Component {
    void add(Component component);
    void remove(Component component);
    Component get();
    void plant();
}

public class Book implements Component{
    private String id;
    private String name;
    private Integer price;

    public Book(String id, String name, Integer price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    @Override
    public void add(Component component) {
        throw new RuntimeException("非目录,不支持add操作");
    }

    @Override
    public void remove(Component component) {
        throw new RuntimeException("非目录,不支持remove操作");
    }

    @Override
    public Component get() {
        return this;
    }
    
    /** 书只打印名字和价格*/
    @Override
    public void plant() {
        System.out.println("  " + name +"(" + price +")");
    }

}

public class Catalogue implements Component{
    private String id;
    private String name;
    private List<Component> items;
    private int root;

    public Catalogue(String id, String name, List<Component> items, int root) {
        this.id = id;
        this.name = name;
        this.items = items;
        this.root = root;
    }

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

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

    @Override
    public Component get() {
        return this;
    }

    /** 目录打印所有书和子目录,用root记录目录层次*/
    @Override
    public void plant() {
        System.out.println("--" + name);
        this.items.forEach(a -> {
            for (int i = 0; i < root; i++) {
                System.out.print("  ");
            }
            a.plant();
        });
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号