Skip to content

Instantly share code, notes, and snippets.

@kadru
Created October 14, 2018 18:58
Show Gist options
  • Save kadru/03c33e8649fbd2ac8e268f00ffb6e05e to your computer and use it in GitHub Desktop.
Save kadru/03c33e8649fbd2ac8e268f00ffb6e05e to your computer and use it in GitHub Desktop.
strategy pattern dynamic behavior example
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
@kadru
Copy link
Author

kadru commented Nov 12, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment