programming-examples/ruby/Patterns/strategy.rb

43 lines
664 B
Ruby
Raw Normal View History

2019-11-15 12:59:38 +01:00
# Define a family of algorithms, encapsulate each one, and make them
# interchangeable. Strategy lets the algorithm vary independently from clients that use it.
# Strategies
class StrategyOne
def use
puts "Strategy one"
end
end
class StrategyTwo
def use
puts "Strategy two"
end
end
class StrategyThree
def use
puts "Strategy three"
end
end
# Client
class Context
@@default_strategy = StrategyOne.new
def set_strategy(strategy)
@strategy = strategy
end
def use
@strategy.use
end
end
# Usage
context = Context.new
context.use # => "Strategy one"
context.set_strategy StrategyTwo.new
context.use # => "Strategy two"