Composite objects

A composite object can also be called a container. We'll look at a simple composite object: a deck of individual cards. This is a basic collection. Indeed, it's so basic that we can, without too much struggle, use a simple list object as a deck.

Before designing a new class, we need to ask this question: is using a simple list object appropriate?

We can use random.shuffle() to shuffle the deck and deck.pop() to deal cards into a player's Hand.

Some programmers rush to define new classes as if using a built-in class violates some object-oriented design principle. Avoiding a new class leaves us with the following code snippet:

>>> d = [card(r + 1, s) for r in range(13) for s in iter(Suit)]
>>> random.shuffle(d)
>>> hand = [d.pop(), d.pop()]
>>> hand
[FaceCard(suit=<Suit.Club: '♣'>, rank='J'), Card(suit=<Suit.Spade: '♠'>, rank='2')]

If it's that simple, why write a new class?

Defining a class has the advantage of creating a simplified, implementation-free interface to the object. In the case of the list example shown in the preceding code, it's not clear how much simpler a Deck class would be.

The deck has two use cases. A class definition doesn't seem to simplify things very much. It does have the advantage of concealing the implementation's details. In this example, the details are so trivial that exposing them has little cost.

We're focused primarily on the __init__() method in this chapter, so we'll look at some designs to create and initialize a collection. To design a collection of objects, we have the following three general design strategies:

  • Wrap: This design pattern surrounds an existing collection definition with a simplified interface. This is an example of the more general Facade design pattern.
  • Extend: This design pattern starts with an existing collection class and extends it to add features.
  • Invent: This is designed from scratch. We'll look at this in Chapter 7, Creating Containers and Collections.

These three concepts are central to object-oriented design. Because Python has so many features built into the language, we must always make this choice when designing a class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset