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

将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

public class Composite_Main {
    public static void main(String[] args) {
        //盘子主盘子
        Component plate = new Plate();
        //附盘子1
        Component plate_1 = new Plate();
        //附盘子2
        Component plate_2 = new Plate();
        //水果1  主盘子上
        Component fruit_1 = new Fruit("fruit_1");
        //水果2  附盘子1上
        Component fruit_2 = new Fruit("fruit_2");
        plate_1.add(fruit_2);
        plate.add(plate_1);
        plate.add(plate_2);
        plate.add(fruit_1);
        System.out.println(JSON.toJSONString(plate));
    }
}

interface Component{
    void eat();
    boolean add(Component component);
    boolean remove(int index);
}
class NoSupportException extends RuntimeException{
    public NoSupportException(String message){
        super(message);
    }
}
@Data
class Fruit implements Component{
    private String name;

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

    @Override
    public void eat() {
        System.out.println("吃水果喽...");
    }
    @Override
    public boolean add(Component component) {
        throw new NoSupportException("水果没有添加的赋能哦");
    }
    @Override
    public boolean remove(int index) {
        throw new NoSupportException("水果没有祛除的赋能哦");
    }
}
@Data
class Plate implements Component{
    private List<Component> components;
    public Plate() {
        this.components = new CopyOnWriteArrayList<>();
    }

    @Override
    public void eat() {
        throw new NoSupportException("盘子不能吃哦");
    }
    @Override
    public boolean add(Component component) {
        if (CollectionUtils.isEmpty(components)){
            this.components = new CopyOnWriteArrayList<>();
        }
        this.components.add(component);
        return false;
    }

    @Override
    public boolean remove(int index) {
        if (CollectionUtils.isEmpty(components)){
            return Boolean.FALSE;
        }
        components.remove(index);
        return Boolean.TRUE;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值