Fluent APIs for factories

In Python, a fluent interface is built by creating methods that return the self instance variable. Each method can set some of the object's state. By returning self, the functions can be chained together.

We might have X().a().b() in an object notation. We can think of it as . The x.a() function is a kind of partial() function that's waiting for b(). We can think of X().a() as if it were an object with another function as its argument value, .

The idea here is that Python offers us two alternatives for initializing state. We can either set all of the values in __init__(), or we can set values in a number of separate methods. In the following example, we'll make the setting of the rank object a fluent method that returns self. Setting the suit object will actually create the Card instance. The following is a fluent Card factory class. An instance must use the two method functions in the required order:

class CardFactory:

def rank(self, rank: int) -> "CardFactory":
self.class_, self.rank_str = {
1: (AceCard, "A"),
11: (FaceCard, "J"),
12: (FaceCard, "Q"),
13: (FaceCard, "K"),
}.get(
rank, (Card, str(rank))
)
return self

def suit(self, suit: Suit) -> Card:
return self.class_(self.rank_str, suit)

The rank() method updates the state of the constructor, and the suit() method actually creates the final Card object. The type hint for the rank() function shows the function returning a CardFactory object. Because the class is not fully defined, the name isn't known, and a quoted string has to be used. The mypy tool will resolve the string type name to create a circular reference from the class to itself.

This factory class can be used as follows:

card8 = CardFactory() 
deck8 = [card8.rank(r + 1).suit(s) for r in range(13) for s in Suit]

First, we create a factory instance, then we use that instance to create the Card instances. This doesn't materially change how __init__() itself works in the Card class hierarchy. It does, however, change the way that our client application creates objects.

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

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