Created
June 5, 2014 21:06
-
-
Save matsumonkie/b9a6590dd852f3077ba9 to your computer and use it in GitHub Desktop.
decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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