打字猴:1.700468372e+09
1700468372 组合模式的通用类图,如图21-6所示。
1700468373
1700468374
1700468375
1700468376
1700468377 图21-6 组合模式通用类图
1700468378
1700468379 我们先来说说组合模式的几个角色:
1700468380
1700468381 ❑Component抽象构件角色
1700468382
1700468383 定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性,比如我们例子中的getInfo就封装到了抽象类中。
1700468384
1700468385 ❑Leaf叶子构件
1700468386
1700468387 叶子对象,其下再也没有其他的分支,也就是遍历的最小单位。
1700468388
1700468389 ❑Composite树枝构件
1700468390
1700468391 树枝对象,它的作用是组合树枝节点和叶子节点形成一个树形结构。
1700468392
1700468393 我们来看组合模式的通用源代码,首先看抽象构件,它是组合模式的精髓,如代码清单21-18所示。
1700468394
1700468395 代码清单21-18 抽象构件
1700468396
1700468397 public abstract class Component{
1700468398
1700468399 //个体和整体都具有的共享
1700468400
1700468401 public void doSomething(){
1700468402
1700468403 //编写业务逻辑
1700468404
1700468405 }
1700468406
1700468407 }
1700468408
1700468409 组合模式的重点就在树枝构件,其通用代码如代码清单21-19所示。
1700468410
1700468411 代码清单21-19 树枝构件
1700468412
1700468413 public class Composite extends Component{
1700468414
1700468415 //构件容器
1700468416
1700468417 private ArrayList<Component>componentArrayList=new ArrayList<Component>();
1700468418
1700468419 //增加一个叶子构件或树枝构件
1700468420
1700468421 public void add(Component component){
[ 上一页 ]  [ :1.700468372e+09 ]  [ 下一页 ]