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

被折叠的 条评论
为什么被折叠?



