Design Patterns in Ruby [Digest 5] Composite

本文介绍了一种设计模式——组合模式,该模式允许将简单对象和复杂对象统一处理,通过递归方式实现树形结构的深度优先遍历。以制作蛋糕为例,展示了如何通过组合模式组织任务并计算总耗时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When we want to build up bigger objects from small sub-objects those build up on the sub-sub-objects then there is a Composite Pattern.

The key point of the pattern is that complex objects and simple objects are treated the same way.

 

The GoF called the design pattern for our “the sum acts like one of the parts” situation the Composite pattern.  

The Composite of objects just looks like invocating the method of each composite objects included in the composite.

 

DFS of the Tree?  Recursion!

 

The writter gives the cack making example code:

 

 

class Task
  attr_reader :name
  def initialize(name)
    @name = name
  end
  def get_time_required
    0.0
  end
end

 

 

class AddDryIngredientsTask < Task
  def initialize
    super('Add dry ingredients')
  end
  def get_time_required
    1.0 # 1 minute to add flour and sugar
  end
end

class MixTask < Task
  def initialize
    super('Mix that batter up!')
  end
  def get_time_required
    3.0 # Mix for 3 minutes
  end
end

class CompositeTask < Task
  def initialize(name)
    super(name)
    @sub_tasks = []
  end
  def add_sub_task(task)
    @sub_tasks << task
  end
  def remove_sub_task(task)
    @sub_tasks.delete(task)
  end
  def get_time_required
    time=0.0
    @sub_tasks.each {|task| time += task.get_time_required}
    time
  end
end

class MakeBatterTask < CompositeTask
  def initialize
    super('Make batter')
    add_sub_task( AddDryIngredientsTask.new )
    add_sub_task( AddLiquidsTask.new )
    add_sub_task( MixTask.new )
  end
end

class MakeCakeTask < CompositeTask
  def initialize
    super('Make cake')
    add_sub_task( MakeBatterTask.new )
    add_sub_task( FillPanTask.new )
    add_sub_task( BakeTask.new )
    add_sub_task( FrostTask.new )
    add_sub_task( LickSpoonTask.new )
  end
end

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值