Hello all.
Ok, ok, I'll give more detail on what I'm up to.
In an effort to learn much more Ruby (and more software technique in
general), I'm working through the O'Reilly book "Head First Design
Patterns" (Gang-of-four rewritten).
So, the first "pattern" (not really a pattern officially) is the
Strategy Pattern.
Duck class is copied below.
My question is this: The :quackDelegate and :flyDelegate are written in
Java/C# as object instances of an interface. Clearly I've ditched the
interface itself, but the rest is pretty much as described in the book.
So, my initial question is: Since ruby has no interfaces, and obeys
duck-typing, is there a more-terse implementation of the below that is
more "The Ruby Way" ?
Much thanks for your sage advice.
---------- duck.rb ----------------
class Duck
attr :quackDelegate, :flyDelegate
def performQuack
@quackDelegate.quack
end
def performFly
@flyDelegate.fly
end
def swim
"All ducks float, even decoys!"
end
def setFlyDelegate(fd)
@flyDelegate = fd
end
end
class FlyWithWings
def fly
"I'm flying!"
end
end
class FlyNoWay
def fly
"I can't fly"
end
end
class FlyRocketPowered
def fly
"I'm flying Rocket Powered!!"
end
end
class Quack
def quack
"Quack"
end
end
class MuteQuack
def quack
"<< Silence >>"
end
end
class Squeak
def quack
"Squeak"
end
end
class MallardDuck < Duck
def initialize
@quackDelegate = Quack.new
@flyDelegate = FlyWithWings.new
end
end
class ModelDuck < Duck
def initialize
@flyDelegate = FlyNoWay.new
@quackDelegate = Quack.new
end
End
----------- end duck.rb -----------------
------------ duck_test.rb ---------------
require 'test/unit'
require 'duck'
class DuckTest < Test::Unit::TestCase
def testMallard
mallardDuck = MallardDuck.new
assert_equal "Quack", mallardDuck.performQuack
assert_equal "I'm flying!", mallardDuck.performFly
end
def testModelDuck
modelDuck = ModelDuck.new
assert_equal "Quack", modelDuck.performQuack
assert_equal "I can't fly", modelDuck.performFly
modelDuck.setFlyDelegate FlyRocketPowered.new
assert_equal "I'm flying Rocket Powered!!", modelDuck.performFly
end
end
-------------- end duck_test.rb ----------
Peter J. Fitzgibbons
Applications Manager
Lakewood Homes - "The American Dream Builder"(r)
Peter.Fitzgibbons@Lakewoodhomes.net
(847) 884-8800