Today’s patterns

Observer and Composite
___________________________________________

Observer

"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

notify_observers

within base

attribute= method(s)

.

Add and Remove Observers with

<<

and

.delete

, e.g.

    def add_observer(o)
      @observer << o
    end
    def delete_observer(o)
      @observers.delete(o)
    end

Iterate through

@observers |o|

, e.g.

def notify_observers
  @observers.each do |o|
    o.update(self)
  end
end

For each one,

o.update(self)

# If the observer class e.g. 'payroll' has an

def update(item) ... end

method.

Composite

"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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s