The Strategy Pattern really resolves to “composition” in practice. This OO technique says to take components that could change at runtime and encapsulate them in their own objects. The master-object is then “composed” of instances of the dependent clasess.
class Duck def fly puts â€˜Flap Flapâ€™ end def quack puts â€˜Quack!â€™ end end d = <span class="constant">Duck.new d.flap d.quack
Flap Flap Quack!
So now handle the en-user request to have ducks with different flap :
class FlapWings def fly puts â€˜Flap Flapâ€™ end end class FlapSoaring def fly puts â€˜Soaring in the windâ€™ end end class Duck def initialize (flapInstance) @flapDelegate = flapInstance end def changeFlap(flapInstance) @flapDelegate = flapInstance end def fly @flapDelegate.fly end def quack puts â€˜Quack!â€™ end end mallard = Duck.new(FlapWings.new) mallard.fly mallard.quack mallard.changeFlap(FlapSoaring.new) mallard.fly
Now produces :
Flap Flap Quack! Soaring in the wind
This example looks trivial. The technique is powerful. Behold that in Java/C#, this requires a lot of effort including Inheritance and Interfaces.
Nice that Ruby allows this run-time change through duck-typing!!