Stateless objects without __init__()

The following is an example of a degenerate class that doesn't need an __init__() method. It's a common design pattern for Strategy objects. A Strategy object is plugged into some kind of master or owner object to implement an algorithm or decision. The Strategy object often depends on data in the master object; the Strategy object may not have any data of its own. We often design strategy classes to follow the Flyweight design pattern so we can avoid internal storage in the strategy instance. All values can be provided to a Strategy object as method argument values. In some cases, a strategy object can be stateless; in this instance, it is more a collection of method functions than anything else.

In the following examples, we'll show both stateless and stateful strategy class definitions. We'll start with the strategy for making some of the player decisions based on the state of the Hand object.

In this case, we're providing the gameplay decisions for a Player instance. The following is an example of a (dumb) strategy to pick cards and decline other bets:

class GameStrategy:

def insurance(self, hand: Hand) -> bool:
return False

def split(self, hand: Hand) -> bool:
return False

def double(self, hand: Hand) -> bool:
return False

def hit(self, hand: Hand) -> bool:
return sum(c.hard for c in hand.cards) <= 17

Each method requires the current Hand object as an argument value. The decisions are based on the available information; that is, on the dealer's cards and the player's cards. The result of each decision is shown in the type hints as a Boolean value. Each method returns True if the player elects to perform the action.

We can build a single instance of this strategy for use by various Player instances, as shown in the following code snippet:

dumb = GameStrategy() 

We can imagine creating a family of related strategy classes, each one using different rules for the various decisions a player is offered in Blackjack.

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

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