1 – Strategy Pattern

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.

Example:

[ruby]
class Duck
def fly
puts ‘Flap Flap’
end

def quack
puts ‘Quack!’
end
end

d = Duck.new
d.flap
d.quack
[/ruby]

Produces:

[text]
Flap Flap
Quack!
[/text]

So now handle the en-user request to have ducks with different flap :
[ruby]
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
[/ruby]

Now produces :
[text]
Flap Flap
Quack!
Soaring in the wind
[/text]

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s