Skip to content

Instantly share code, notes, and snippets.

@erubboli
Created September 11, 2010 10:20
Show Gist options
  • Save erubboli/575067 to your computer and use it in GitHub Desktop.
Save erubboli/575067 to your computer and use it in GitHub Desktop.
module Leaf
def land_size
@land_size || 0
end
end
module Composite
def append_child(child)
@children << child
end
def remove_child(child)
@children.delete child
end
def land_size
@children.inject(0){ |sum, child| sum + child.land_size }
end
end
class Building
include Leaf
def initialize( land_size )
@land_size = land_size
end
end
class Neighbourhood
include Leaf
include Composite
def initialize
@children = []
end
end
class City
include Composite
def initialize
@children = []
end
end
#example
cervia = City.new
terme = Neighbourhood.new
pinarella = Neighbourhood.new
pinarella.append_child Building.new( 400 )
pinarella.append_child Building.new( 600 )
terme.append_child Building.new( 200 )
terme.append_child Building.new( 1000 )
cervia.append_child pinarella
cervia.append_child terme
cervia.append_child Building.new( 500 )
puts "cervia size: #{cervia.land_size}" #=>cervia size: 2700
puts "pinarella size: #{pinarella.land_size}" #=>pinarella size: 1000
puts "terme size: #{terme.land_size}" #=> terme size: 1200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment