Skip to content

Instantly share code, notes, and snippets.

@geckofu
Last active August 29, 2015 14:15
Show Gist options
  • Save geckofu/91c88ca1a5c9ac233b2d to your computer and use it in GitHub Desktop.
Save geckofu/91c88ca1a5c9ac233b2d to your computer and use it in GitHub Desktop.
design patterns in ruby
# inherite way:
# - engine details are probably exposed to the Car
# - hard for engine-less vehicle's adaption
class Vehicle
def start_engine
end
def stop_engine
end
end
class Car < Vehicle
def sunday_drive
start_engine
stop_engine
end
end
# compose way
# - prevent engine-related details exposed to Vehicle
# the only way a car can do to its engine is by working through the public interface
# - open up the possibility of other kinds of engines. (engine inheritance)
class Engine
def start
end
def stop
end
end
class Car
def initialize
@engine = Engine.new
end
def start_engine
@engine.start
end
def stop_engine
@engine.stop
end
def sunday_drive
start_engine
stop_engine
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment