# Head First Design Patterns - Strategy Pattern \[was: Java/C# "interface" in Ruby ?\]

**URL:** <https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101>\
**Category:** ruby-talk\
**Created:** [11 August 2005 18:20 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101 "2005-08-11T18:20:18Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Peter\_Fitzgibbons1](https://avatars.discourse-cdn.com/v4/letter/p/aca169/32.png) [@Peter\_Fitzgibbons1](https://rubytalk.org/u/Peter_Fitzgibbons1)\
**Post date:** [11 August 2005 18:20 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101/1 "2005-08-11T18:20:18Z")

</div>

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  
&nbsp;&nbsp;attr :quackDelegate, :flyDelegate

&nbsp;&nbsp;def performQuack  
&nbsp;&nbsp;&nbsp;&nbsp;@quackDelegate.quack  
&nbsp;&nbsp;end  
&nbsp;&nbsp;  
&nbsp;&nbsp;def performFly  
&nbsp;&nbsp;&nbsp;&nbsp;@flyDelegate.fly  
&nbsp;&nbsp;end  
&nbsp;&nbsp;  
&nbsp;&nbsp;def swim  
&nbsp;&nbsp;&nbsp;&nbsp;"All ducks float, even decoys!"  
&nbsp;&nbsp;end  
&nbsp;&nbsp;  
&nbsp;&nbsp;def setFlyDelegate(fd)  
&nbsp;&nbsp;&nbsp;&nbsp;@flyDelegate = fd  
&nbsp;&nbsp;end  
&nbsp;&nbsp;  
end

class FlyWithWings  
&nbsp;&nbsp;def fly  
&nbsp;&nbsp;&nbsp;&nbsp;"I'm flying!"  
&nbsp;&nbsp;end  
end

class FlyNoWay  
&nbsp;&nbsp;def fly  
&nbsp;&nbsp;&nbsp;&nbsp;"I can't fly"  
&nbsp;&nbsp;end  
end

class FlyRocketPowered  
&nbsp;&nbsp;def fly  
&nbsp;&nbsp;&nbsp;&nbsp;"I'm flying Rocket Powered!!"  
&nbsp;&nbsp;end  
end

class Quack  
&nbsp;&nbsp;def quack  
&nbsp;&nbsp;&nbsp;&nbsp;"Quack"  
&nbsp;&nbsp;end  
end

class MuteQuack  
&nbsp;&nbsp;def quack  
&nbsp;&nbsp;&nbsp;&nbsp;"\<\< Silence \>\>"  
&nbsp;&nbsp;end  
end

class Squeak  
&nbsp;&nbsp;def quack  
&nbsp;&nbsp;&nbsp;&nbsp;"Squeak"  
&nbsp;&nbsp;end  
end

class MallardDuck \< Duck  
&nbsp;&nbsp;def initialize  
&nbsp;&nbsp;&nbsp;&nbsp;@quackDelegate = Quack.new  
&nbsp;&nbsp;&nbsp;&nbsp;@flyDelegate = FlyWithWings.new  
&nbsp;&nbsp;end  
end

class ModelDuck \< Duck  
&nbsp;&nbsp;def initialize  
&nbsp;&nbsp;&nbsp;&nbsp;@flyDelegate = FlyNoWay.new  
&nbsp;&nbsp;&nbsp;&nbsp;@quackDelegate = Quack.new  
&nbsp;&nbsp;end  
End  
----------- end duck.rb -----------------

------------ duck\_test.rb ---------------  
require 'test/unit'  
require 'duck'

class DuckTest \< Test::Unit::TestCase  
&nbsp;&nbsp;def testMallard  
&nbsp;&nbsp;&nbsp;&nbsp;mallardDuck = MallardDuck.new  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "Quack", mallardDuck.performQuack  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "I'm flying!", mallardDuck.performFly  
&nbsp;&nbsp;end

&nbsp;&nbsp;def testModelDuck  
&nbsp;&nbsp;&nbsp;&nbsp;modelDuck = ModelDuck.new  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "Quack", modelDuck.performQuack  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "I can't fly", modelDuck.performFly  
&nbsp;&nbsp;&nbsp;&nbsp;modelDuck.setFlyDelegate FlyRocketPowered.new  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "I'm flying Rocket Powered!!", modelDuck.performFly  
&nbsp;&nbsp;end  
&nbsp;&nbsp;  
end  
-------------- end duck\_test.rb ----------

Peter J. Fitzgibbons  
Applications Manager  
Lakewood Homes - "The American Dream Builder"(r)  
[Peter.Fitzgibbons@Lakewoodhomes.net](mailto:Peter.Fitzgibbons@Lakewoodhomes.net)  
(847) 884-8800

---

<div class="post-metadata">

**Author:** ![J-Van](https://avatars.discourse-cdn.com/v4/letter/j/bc8723/32.png) [@J-Van](https://rubytalk.org/u/J-Van)\
**Post date:** [11 August 2005 20:26 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101/2 "2005-08-11T20:26:03Z")

</div>

I have no idea if it's appliable in this case, but Ruby's standard  
library comes with a Delgate something or other. Might be helpful.

> **···**
>
> On 8/11/05, Peter Fitzgibbons \<Peter.Fitzgibbons@lakewoodhomes.net\> wrote:
> 
> > 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.

---

<div class="post-metadata">

**Author:** ![Dave\_Burt2](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/dave_burt2/32/2036_2.png) [@Dave\_Burt2](https://rubytalk.org/u/Dave_Burt2)\
**Post date:** [11 August 2005 21:21 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101/3 "2005-08-11T21:21:10Z")

</div>

Peter Fitzgibbons wrote:

> ...  
> 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.

This looks like exactly what mixins are for - you can put the implementation  
itself in a module and then include it rather than using delegation and  
having extra objects with one-method floating around.

class Duck  
&nbsp;&nbsp;def swim() "All ducks float, even decoys!" end  
end

module FlyWithWings  
&nbsp;&nbsp;def fly() "I'm flying!" end  
end

# other Flys and Quacks as above, the only change is class -\> module...

class MallardDuck \< Duck  
&nbsp;&nbsp;include Quack  
&nbsp;&nbsp;include FlyWithWings  
end

class ModelDuck \< Duck  
&nbsp;&nbsp;include FlyNoWay  
&nbsp;&nbsp;include Quack  
end

# next file, duck\_test.rb  
require 'test/unit'  
require 'duck'

class DuckTest \< Test::Unit::TestCase  
&nbsp;&nbsp;def testMallard  
&nbsp;&nbsp;&nbsp;&nbsp;mallardDuck = MallardDuck.new  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "Quack", mallardDuck.quack # no intermediate method needed  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "I'm flying!", mallardDuck.fly  
&nbsp;&nbsp;end

&nbsp;&nbsp;def testModelDuck  
&nbsp;&nbsp;&nbsp;&nbsp;modelDuck = ModelDuck.new  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "Quack", modelDuck.quack  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "I can't fly", modelDuck.fly  
&nbsp;&nbsp;&nbsp;&nbsp;modelDuck.extend FlyRocketPowered  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal "I'm flying Rocket Powered!!", modelDuck.fly  
&nbsp;&nbsp;end

end

And there you have it - much nicer!

If you do want to use delegation (I don't know why), you can use a class  
with a single class- (like Java static-) method; then you don't need to use  
FlyWithWings.new, you just pass the FlyWithWings class:

class FlyWithWings  
&nbsp;&nbsp;def self.fly() "I'm flying!" end  
end  
# ... (only changes are "def fly()" -\> "def self.fly()")  
class MallardDuck \< Duck  
&nbsp;&nbsp;def initialize  
&nbsp;&nbsp;&nbsp;&nbsp;@flyDelegate = FlyWithWings  
# ... (only changes are "= FlyWithWings.new" -\> "= FlyWithWings")

Cheers,  
Dave

---

<div class="post-metadata">

**Author:** ![Jim\_Weirich1](https://avatars.discourse-cdn.com/v4/letter/j/73ab20/32.png) [@Jim\_Weirich1](https://rubytalk.org/u/Jim_Weirich1)\
**Post date:** [12 August 2005 01:16 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101/4 "2005-08-12T01:16:52Z")

</div>

Although Peter's demo didn't illustrate it, the key to the strategy pattern is  
that the strategy can be dynamically chosen (and changed) at runtime.

However, including modules would be an interesting variation on the Template  
Method Pattern, which is similar to Strategy, except that it uses inheritance  
to get the variation (and therefore can't change at runtime).

> **···**
>
> On Thursday 11 August 2005 05:21 pm, Dave Burt wrote:
> 
> > This looks like exactly what mixins are for - you can put the  
> > implementation itself in a module and then include it rather than using  
> > delegation and having extra objects with one-method floating around.
> 
> --  
> -- Jim Weirich jim@weirichhouse.org [http://onestepback.org](http://onestepback.org)  
> -----------------------------------------------------------------  
> "Beware of bugs in the above code; I have only proved it correct,  
> not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)

---

<div class="post-metadata">

**Author:** ![Dave\_Burt1](https://avatars.discourse-cdn.com/v4/letter/d/ebca7d/32.png) [@Dave\_Burt1](https://rubytalk.org/u/Dave_Burt1)\
**Post date:** [12 August 2005 03:41 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101/5 "2005-08-12T03:41:11Z")

</div>

> Although Peter's demo didn't illustrate it, the key to the strategy pattern is  
> that the strategy can be dynamically chosen (and changed) at runtime.

While the solution I gave is able to do that, thanks to Ruby's ease of  
reflection, if that's the case, maybe you do want to use delegation  
like I did above.

If a Strategy is a single function, I'd probably do it more like this,  
though:

Quack = proc do  
&nbsp;&nbsp;puts "Quack!"  
end

DaffyQuack = proc do  
&nbsp;&nbsp;puts "Consequences, schmonsequences, as long as I'm rich!"  
end

Class Duck  
&nbsp;&nbsp;def initialize() @quacker = Quack end  
&nbsp;&nbsp;def quack(\*args, &block) @quacker.call(\*args, &block) end  
&nbsp;&nbsp;def attr\_writer :quacker  
end

daffy = Duck.new  
daffy.quack #=\> "Quack"  
daffy.quacker = DaffyQuack  
daffy.quack #=\> "Consequences, schmonsequences, as long as I'm rich!"

For multi-function/method strategies, you might consider using  
Forwardable to delegate specific methods to modules or objects in  
instance variables.

Cheers,  
Dave

---

<div class="post-metadata">

**Author:** ![Jim\_Weirich1](https://avatars.discourse-cdn.com/v4/letter/j/73ab20/32.png) [@Jim\_Weirich1](https://rubytalk.org/u/Jim_Weirich1)\
**Post date:** [12 August 2005 05:27 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101/6 "2005-08-12T05:27:32Z")

</div>

[... proc based solution elided ...]

Agreed, unless the strategy object requires state. E.g.

&nbsp;&nbsp;class Employee  
&nbsp;&nbsp;&nbsp;&nbsp;attr\_accessor :payment\_strategy  
&nbsp;&nbsp;&nbsp;&nbsp;def pay  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@payment\_strategy.pay  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;class HourlyStrategy  
&nbsp;&nbsp;&nbsp;&nbsp;def initialize(hourly\_rate, timecards)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@rate = hourly\_rate  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@timecards = timecards  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;def pay  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@timecards.inject(0.0) { |s, tc| s + tc.calculate\_pay(@rate) }  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;class SalaryStrategy  
&nbsp;&nbsp;&nbsp;&nbsp;def initialize(salary)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@weekly\_salary = salary  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;def pay  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@weekly\_salary  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

> **···**
>
> On Thursday 11 August 2005 11:41 pm, dave.burt@gmail.com wrote:
> 
> > If a Strategy is a single function, I'd probably do it more like this,  
> > though:
> 
> --  
> -- Jim Weirich jim@weirichhouse.org [http://onestepback.org](http://onestepback.org)  
> -----------------------------------------------------------------  
> "Beware of bugs in the above code; I have only proved it correct,  
> not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)

---

<div class="post-metadata">

**Author:** ![Dave\_Burt2](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/dave_burt2/32/2036_2.png) [@Dave\_Burt2](https://rubytalk.org/u/Dave_Burt2)\
**Post date:** [12 August 2005 07:36 UTC](https://rubytalk.org/t/head-first-design-patterns-strategy-pattern-was-java-c-interface-in-ruby/20101/7 "2005-08-12T07:36:12Z")

</div>

Jim Weirich wrote:

> > If a Strategy is a single function, I'd probably do it more like this,  
> > though:
> 
> [... proc based solution elided ...]
> 
> Agreed, unless the strategy object requires state. E.g.  
> ...  
> class HourlyStrategy  
> &nbsp;&nbsp;&nbsp;def initialize(hourly\_rate, timecards)  
> ...

You can put state in procs, too - using local variables rather than instance  
variables. (I'm sorry, I'm learning Haskell.)

Of course, the following way is more stupid than Jim's way in the parent  
post, which allows not only state, but also private helper methods.

HourlyStrategy = proc do |hourly\_rate, timecards|  
&nbsp;&nbsp;proc do  
&nbsp;&nbsp;&nbsp;&nbsp;timecards.inject(0.0) { |s, tc| s + tc.calculate\_pay(hourly\_rate) }  
&nbsp;&nbsp;end  
end

I was going to say that this is more stupid than Jim's way, and his is  
definitely more Java-ish, but I kind of like the look of that.

Cheers,  
Dave

> **···**
>
> > On Thursday 11 August 2005 11:41 pm, dave.burt@gmail.com wrote:
