`
jlaky
  • 浏览: 42031 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Design Patterns in Ruby [Digest 5] Composite

阅读更多

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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics