Java设计模式(6) -- 组合

Composite

 

英文简单描述

Intent
You want to represent part-whole hierarchies of objects.
Composite lets clients treat individual objects and compositions of objects uniformly.

How to
Component
declares the interface for objects in the composition.
implements default behavior for the interface common to all classes, as appropriate.
Leaf
represents leaf objects in the composition. A leaf has no children.
Composite
defines behavior for components having children.
implements child-related operations in the Component interface.

Known cases

File System(Dir or File)
Filter(AndSpec、OrSpec、EqualSpec)

UML

 

权衡:

add和remove这些管理孩子的方法是放到component接口中好呢,还是放到Composite中好呢?

(1)放到component接口中,提供默认的实现,抛出异常,如:

  

Leaf类不提供对其的实现,如果client调用了,则抛出异常;Composite类实现添加child的功能;这样不用判断其类型,可以统一接口

(2)将其下移到Composite,但是不能统一接口

 

代码:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值