-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.rb
More file actions
137 lines (97 loc) · 1.83 KB
/
composite.rb
File metadata and controls
137 lines (97 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class Task
attr_accessor :name, :parent
def initialize( name )
@name = name
@parent = nil
end
def get_time_required
raise "Calling abstract method: \"get_time_required\" in \"#{self.class}\" class"
end
def total_number_basic_tasks
1
end
end
class CompositeTask < Task
def initialize( name )
super ( name )
@sub_tasks = []
end
def <<( task )
@sub_tasks << task
task.parent = self
end
def remove_sub_task( task )
@sub_tasks.delete task
task.parent = nil
end
def []( index )
@sub_tasks[index]
end
def []=( index, task)
@sub_tasks[index] = task
end
def get_time_required
@sub_tasks.inject(0){ |time, task| time + task.get_time_required }
end
def total_number_basic_tasks
@sub_tasks.inject(0){ |total, task| total + task.total_number_basic_tasks }
end
end
class AddDryIngredientsTask < Task
def initialize
super( 'add dry ingredients' )
end
def get_time_required
1.0
end
end
class AddLiquidIngredientsTask < Task
def initialize
super( 'add liquid ingredients' )
end
def get_time_required
2.0
end
end
class MixTask < Task
def initialize
super ( 'Mix that batter up!' )
end
def get_time_required
3.0
end
end
class FillPanTask < Task
def initialize
super 'Fill pan task'
end
def get_time_required
3.0
end
end
class MakeBatterTask < CompositeTask
def initialize
super( 'make batter task' )
self.<<( AddDryIngredientsTask.new )
self.<< AddLiquidIngredientsTask.new
self.<< MixTask.new
end
end
class MakeCake < CompositeTask
def initialize
super 'Make Cake'
end
end
task = FillPanTask.new
mbt = MakeCake.new
mbt << MakeBatterTask.new
mbt << task
mbt[2] = MixTask.new
puts mbt.get_time_required
puts mbt[1].name
puts mbt[2].name
while task
puts "task #{task.name}"
task = task.parent
end
puts mbt.total_number_basic_tasks