Created
October 14, 2018 18:58
-
-
Save kadru/03c33e8649fbd2ac8e268f00ffb6e05e to your computer and use it in GitHub Desktop.
strategy pattern dynamic behavior example
This file contains hidden or 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
module RunStrategies | |
class RunStrategyInterface | |
def self.run(name) | |
raise "Run method has not been implemented!" | |
end | |
end | |
class Jog < RunStrategyInterface | |
def self.run(name) | |
puts "#{name} is now jogging at a comfortable pace." | |
end | |
end | |
class Sprint < RunStrategyInterface | |
def self.run(name) | |
puts "#{name} is now sprinting full speeed!" | |
end | |
end | |
class Marathon < RunStrategyInterface | |
def self.run(name) | |
puts "#{name} is now running at a steady pace." | |
end | |
end | |
end | |
class Runner | |
attr_reader :name, :strategy | |
attr_writer :strategy | |
def initialize(name, strategy) | |
@name = name | |
@strategy = strategy | |
end | |
def run | |
@strategy.run(@name) | |
end | |
end | |
class Race | |
attr_reader :runners | |
def initialize(runners) | |
@runners = runners | |
end | |
def start | |
@runners.each { |runner| runner.run } | |
end | |
end | |
alice_ruby = Runner.new("Alice Ruby", RunStrategies::Jog) | |
florence_joyner = Runner.new("Florence Joyner", RunStrategies::Sprint) | |
eliud_kipchoge = Runner.new("Eliud Kipchoge", RunStrategies::Marathon) | |
race = Race.new([alice_ruby, florence_joyner, eliud_kipchoge]) | |
race.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This pattern is particularly useful when you have an object that needs to be able to execute a single behavior in different ways at different times.