Observer and Composite
"An array to hold the observers, a couple of methods to manage the array and a method to notify the observers in the array"
Add and Remove Observers with
def add_observer(o) @observer << o end def delete_observer(o) @observers.delete(o) end
def notify_observers @observers.each do |o| o.update(self) end end
For each one,
# If the observer class e.g. 'payroll' has an
def update(item) ... end
"A base class ('Component'), lowest level detail classes ('leaves') and higher level class ('Composites') built from those leaves.
The base component class has attributes/methods that are common to all items.
The leaf class overrides initialize(e.g.name), calls super('e.g. name') and overrides methods that should return different results.
The composite classes inherit (`<`) from the base class, they have an initialize method, which calls super('params') and which defines an empty array `@sub_tasks=`. Also there are add_sub_task and remove_sub_task methods.
def add_sub_task(task) @sub_tasks << task end def remove_sub_task(task) @sub_tasks.delete(task) end
The composite class also overrides methods in the base component, similar to the leafs. The over-ridden method(s) can iterate through sub tasks and perform actions on each one.