Skip to content

Instantly share code, notes, and snippets.

@matsumonkie
Created June 5, 2014 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsumonkie/b9a6590dd852f3077ba9 to your computer and use it in GitHub Desktop.
Save matsumonkie/b9a6590dd852f3077ba9 to your computer and use it in GitHub Desktop.
decorator
require 'delegate'
#----------------------------------------------------------------------
class Logger
DEFAULT_FORMATTER = '%d'
def initialize(formatter)
@formatter = formatter || DEFAULT_FORMATTER
end
def log(*infos)
puts @formatter % infos
end
end
#----------------------------------------------------------------------
class MonitoredCar < SimpleDelegator
def initialize(car, logger)
super(car)
@logger = logger
end
def accelerate(acc:, duration:)
super.tap {
@logger.log(car, speed)
}
end
def slow_down(acc:, duration:)
super.tap {
@logger.log(car, speed)
}
end
end
#----------------------------------------------------------------------
class Car
attr_reader :car, :speed
def initialize(car)
@car = car
@speed = 0
end
def accelerate(acc:, duration:)
delta_speed = acc * duration
@speed += delta_speed
end
def slow_down(acc:, duration:)
delta_speed = acc * duration
@speed -= delta_speed
end
end
#----------------------------------------------------------------------
def main
car = Car.new('Ferrari')
logger = Logger.new('-> The %s is moving at %d km/h')
monitored_car = MonitoredCar.new(car, logger)
monitored_car.accelerate(acc: 10, duration: 5)
monitored_car.slow_down(acc: 10, duration: 3)
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment