Jesús Gabriel y Galán
1/21/2009 6:53:00 PM
Hi,
I have a question about what would be the best way to implement this
functionality. I have a deck class which represents a deck of
something (for example cards), with the functionality you would
expect: cut, shuffle, draw, peek, etc. It basically wraps an array of
objects (for the deck class the objects themselves don't matter).
Now, I need to implement different decks of things for different games
or for different games within a game. Those decks don't usually have
other functionality themselves, although some might. They just provide
the objects that the deck will be composed of. For example:
class Deck
def initialize
@deck = []
end
# rest of methods: cut, draw, etc.
end
class AlhambraMoneyDeck < Deck
def initialize
super
AlhambraMoney::types.each do |type|
3.times do
(1..9).each {|value| self << AlhambraMoney.new(type,value)
}
end
end
end
end
Another example:
class DistrictsDeck < Deck
def initialize
super
5.times {self << District.new("Taberna", 1, :green)}
4.times {self << District.new("Mercado", 2, :green)}
4.times {self << District.new("Tienda", 2, :green)}
3.times {self << District.new("Almacen", 3, :green)}
3.times {self << District.new("Puerto", 4, :green)}
2.times {self << District.new("Ayuntamiento", 5, :green)}
# ... many more (this is Citadels, in case you are wondering)
end
end
I am not very happy with this way of doing things, since the
subclasses need to call super and then use the method << to add things
to the deck. As you can see it's not very pretty. What I would like to
ask is what good idiom/design I could use to ease the children
definition. I was thinking of using a class method on deck to pass an
array of objects like:
class TestDeck < Deck
items %w{a b c d e}
end
But I'm worried the code could get messy if the creation of those
objects is a bit more complex, as in the cases I presented above.
Another idea is to call an items method in deck's initialize. The
method should return an array, and children classes would need to
override it:
class Deck
def initialize
@deck = items
end
def items
[]
end
end
class TestDeck < Deck
def items
%w{a b c d e}
end
end
Then, only thing is that subclasses should not override initizalize
without calling super, which I'm not sure how good/bad it is as a well
designed framework.
Well, that's the issue, any ideas are very welcome.
Regards,
Jesus.