Skip to content

Instantly share code, notes, and snippets.

@zacclark
Created March 30, 2011 03:31
Show Gist options
  • Save zacclark/893817 to your computer and use it in GitHub Desktop.
Save zacclark/893817 to your computer and use it in GitHub Desktop.
A basic strategy pattern example in Ruby.
class Duck
def initialize(name = "Ducky")
set_quack
@name = name
end
def quack
@quack_behavior.quack
end
def set_quack(behavior = LoudQuack.new)
if behavior.respond_to?(:set_duck)
behavior.set_duck(self)
end
@quack_behavior = behavior
end
def name
return @name
end
end
class LoudQuack
def quack
puts "QUACK!!!!"
end
end
class QuietQuack
def quack
puts "quack...."
end
end
class NameQuack
def set_duck(duck)
@myduck = duck
end
def quack
puts @myduck.name
end
end
norm = Duck.new
norm.quack
norm.set_quack(QuietQuack.new)
norm.quack
norm.set_quack(NameQuack.new)
norm.quack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment