Examining Dwemthy’s Array composite pattern

Dwemthy’s Array is a 60 lines of code RPG-style adventure game written in Ruby as a part of Why’s Poignant Guide to Ruby to introduce meta-programming.
You’re a rabbit, and armed with your little boomerang, sword and bombs (!), you’re going to meet your doom and defeat Dwemthy’s Array, a dungeon filled with filthy creatures, or perish and go to rabbit’s heaven, where you will eat a lot of lettuce.
To learn more about dwemthy’s array, go right here.
Here is the actual code of Dwemthy’s Array:
class DwemthysArray < Array
alias _inspect inspect
def inspect; "#<#{ self.class }#{ _inspect }>"; end
def method_missing( meth, *args )
answer = first.send( meth, *args )
if first.life <= 0
shift
if empty?
puts "[Whoa. You decimated Dwemthy's Array!]"
else
puts "[Get ready. #{ first.class } has emerged.]"
end
end
answer || 0
end
end
The idea is to make you, the little rabbit, fight whichever monster resides in that grim place.
If you want to train before entering Dwemthy’s array, you could just fight a single mob.
# The rabbit is jealous of all the attention the koala gets,
# so he wants to chop his head off.
r = Rabbit.new k = Koala.new r / k # Sword hit!
Way to go little rabbit. Now, he is definitely ready to enter Dwemthy’s array.
# dwarr is a populated instance of Dwemthy's Array r = Rabbit.new r / dwarr # Sword hit!
As you can see, the rabbit isn’t giving a sword blow to a monster, rather, he hits the array itself.
Dwemthy’s Array behaves just like the elements it is composed of. In this case, monsters.
This type of behavior where “the sum acts as one of the parts” is a pretty common design-pattern, introduced by the GoF as composite.
In order to emulate that with Dwemthy’s Array without making use of inheritance and common interfaces for each components, Why used a nifty little trick: the method_missing method.
When Dwemthy’s Array receives messages it doesn’t know, it simply passes them to the first of its component in itsĀ method_missing hook, which will respond, since he is an evil monster who knows how to receive a sword blow (and to fight back)!
Writing a composite pattern simply by subclassing an array and overriding the method_missing hook isn’t bullet-proof. But if you know what you’re doing, you might just end-up doing a code that’s way shorter, and more readable.
You decide.
3 notes ()
-
locks reblogged this from michael-sokol
-
locks liked this
-
michael-sokol posted this
