上QQ阅读APP看书,第一时间看更新
Wrapping a collection class
The following is a wrapper design that contains an internal collection:
class Deck: def __init__( self ): self._cards = [card6(r+1,s) for r in range(13) for s in (Club, Diamond, Heart, Spade)] random.shuffle( self._cards ) def pop( self ): return self._cards.pop()
We've defined Deck
so that the internal collection is a list
object. The pop()
method of Deck
simply delegates to the wrapped list
object.
We can then create a Hand
instance with the following kind of code:
d= Deck() hand= [ d.pop(), d.pop() ]
Generally, a Facade design pattern or wrapper class contains methods that are simply delegated to the underlying implementation class. This delegation can become wordy. For a sophisticated collection, we may wind up delegating a large number of methods to the wrapped object.