Home > Articles > Programming > Python

  • Print
  • + Share This
This chapter is from the book

1.3. Factory Method Pattern

The Factory Method Pattern is intended to be used when we want subclasses to choose which classes they should instantiate when an object is requested. This is useful in its own right, but can be taken further and used in cases where we cannot know the class in advance (e.g., the class to use is based on what we read from a file or depends on user input).

In this section we will review a program that can be used to create game boards (e.g., a checkers or chess board). The program’s output is shown in Figure 1.3, and the four variants of the source code are in the files gameboard1.py...game-board4.py.*star.jpg

We want to have an abstract board class that can be subclassed to create game-specific boards. Each board subclass will populate itself with its initial layout of pieces. And we want every unique kind of piece to belong to its own class (e.g., BlackDraught, WhiteDraught, BlackChessBishop, WhiteChessKnight, etc.). Incidentally, for individual pieces, we have used class names like WhiteDraught rather than, say, WhiteChecker, to match the names used in Unicode for the corresponding characters.

Figure 1.3

Figure 1.3 The checkers and chess game boards on a Linux console

We will begin by reviewing the top-level code that instantiates and prints the boards. Next, we will look at the board classes and some of the piece classes—starting with hard-coded classes. Then we will review some variations that allow us to avoid hard-coding classes and at the same time use fewer lines of code.

def main():
    checkers = CheckersBoard()
    print(checkers)

    chess = ChessBoard()
    print(chess)

This function is common to all versions of the program. It simply creates each type of board and prints it to the console, relying on the AbstractBoard’s __str__() method to convert the board’s internal representation into a string.

BLACK, WHITE = ("BLACK", "WHITE")

class AbstractBoard:

    def  __init__(self, rows, columns):
         self.board = [[None for _ in range(columns)] for _ in range(rows)]
         self.populate_board()

    def populate_board(self):
        raise NotImplementedError()

    def __str__(self):
        squares = []
        for y, row in enumerate(self.board):
            for x, piece in enumerate(row):
                square = console(piece, BLACK if (y + x) % 2 else WHITE)
                squares.append(square)
            squares.append("\n")
        return "".join(squares)

The BLACK and WHITE constants are used here to indicate each square’s background color. In later variants they are also used to indicate each piece’s color. This class is quoted from gameboard1.py, but it is the same in all versions.

It would have been more conventional to specify the constants by writing: BLACK, WHITE = range(2). However, using strings is much more helpful when it comes to debugging error messages, and should be just as fast as using integers thanks to Python’s smart interning and identity checks.

The board is represented by a list of rows of single-character strings—or None for unoccupied squares. The console() function (not shown, but in the source code), returns a string representing the given piece on the given background color. (On Unix-like systems this string includes escape codes to color the background.)

We could have made the AbstractBoard a formally abstract class by giving it a metaclass of abc.ABCMeta (as we did for the AbstractFormBuilder class; 12 left-arrow.jpg). However, here we have chosen to use a different approach, and simply raise a NotImplementedError exception for any methods we want subclasses to reimplement.

class CheckersBoard(AbstractBoard):

    def __init__(self):
        super().__init__(10, 10)

    def populate_board(self):
        for x in range(0, 9, 2):
            for row in range(4):
                column = x + ((row + 1) % 2)
                self.board[row][column] = BlackDraught()
                self.board[row + 6][column] = WhiteDraught()

This subclass is used to create a representation of a 10 × 10 international checkers board. This class’s populate_board() method is not a factory method, since it uses hard-coded classes; it is shown in this form as a step on the way to making it into a factory method.

class ChessBoard(AbstractBoard):

    def __init__(self):
        super().__init__(8, 8)

    def populate_board(self):
        self.board[0][0] = BlackChessRook()
        self.board[0][1] = BlackChessKnight()
        ...
        self.board[7][7] = WhiteChessRook()
        for column in range(8):
            self.board[1][column] = BlackChessPawn()
            self.board[6][column] = WhiteChessPawn()

This version of the ChessBoard’s populate_board() method—just like the Checkers-Board’s one—is not a factory method, but it does illustrate how the chess board is populated.

class Piece(str):

    __slots__ = ()

This class serves as a base class for pieces. We could have simply used str, but that would not have allowed us to determine if an object is a piece (e.g., using isinstance(x, Piece)). Using __slots__ = () ensures that instances have no data, a topic we’ll discuss later on (§2.6, right-arrow.jpg 65).

class BlackDraught(Piece):

    __slots__ = ()

    def __new__(Class):
        return super().__new__(Class, "\N{black draughts man}")

class WhiteChessKing(Piece):

    __slots__ = ()

    def __new__(Class):
        return super().__new__(Class, "\N{white chess king}")

These two classes are models for the pattern used for all the piece classes. Every one is an immutable Piece subclass (itself a str subclass) that is initialized with a one-character string holding the Unicode character that represents the relevant piece. There are fourteen of these tiny subclasses in all, each one differing only by its class name and the string it holds: clearly, it would be nice to eliminate all this near-duplication.

    def populate_board(self):
        for x in range(0, 9, 2):
            for y in range(4):
                column = x + ((y + 1) % 2)
                for row, color in ((y, "black"), (y + 6, "white")):
                    self.board[row][column] = create_piece("draught",
                            color)

This new version of the CheckersBoard.populate_board() method (quoted from gameboard2.py) is a factory method, since it depends on a new create_piece() factory function rather than on hard-coded classes. The create_piece() function returns an object of the appropriate type (e.g., a BlackDraught or a WhiteDraught), depending on its arguments. This version of the program has a similar Chess-Board.populate_board() method (not shown), which also uses string color and piece names and the same create_piece() function.

def create_piece(kind, color):
    if kind == "draught":
        return eval("{}{}()".format(color.title(), kind.title()))
    return eval("{}Chess{}()".format(color.title(), kind.title()))

This factory function uses the built-in eval() function to create class instances. For example, if the arguments are "knight" and "black", the string to be eval()’d will be "BlackChessKnight()". Although this works perfectly well, it is potentially risky since pretty well anything could be eval()’d into existence—we will see a solution, using the built-in type() function, shortly.

for code in itertools.chain((0x26C0, 0x26C2), range(0x2654, 0x2660)):
    char = chr(code)
    name = unicodedata.name(char).title().replace("  ", "")
    if name.endswith("sMan"):
        name = name[:-4]
    exec("""\
class {}(Piece):

    __slots__ = ()

    def __new__(Class):
        return super().__new__(Class,  "{}")""".format(name, char))

Instead of writing the code for fourteen very similar classes, here we create all the classes we need with a single block of code.

The itertools.chain() function takes one or more iterables and returns a single iterable that iterates over the first iterable it was passed, then the second, and so on. Here, we have given it two iterables, the first a 2-tuple of the Unicode code points for black and white checkers pieces, and the second a range-object (in effect, a generator) for the black and white chess pieces.

For each code point we create a single character string (e.g., “horse.jpg”) and then create a class name based on the character’s Unicode name (e.g., “black chess knight” becomes BlackChessKnight). Once we have the character and the name we use exec() to create the class we need. This code block is a mere dozen lines—compared with around a hundred lines for creating all the classes individually.

Unfortunately, though, using exec() is potentially even more risky than using eval(), so we must find a better way.

DRAUGHT, PAWN, ROOK, KNIGHT, BISHOP, KING, QUEEN = ("DRAUGHT", "PAWN",
        "ROOK", "KNIGHT", "BISHOP", "KING", "QUEEN")

class CheckersBoard(AbstractBoard):
    ...

    def populate_board(self):
        for x in range(0, 9, 2):
            for y in range(4):
                column = x + ((y + 1) % 2)
                for row, color in ((y, BLACK), (y + 6, WHITE)):
                    self.board[row][column] = self.create_piece(DRAUGHT,
                            color)

This CheckersBoard.populate_board() method is from gameboard3.py. It differs from the previous version in that the piece and color are both specified using constants rather than easy to mistype string literals. Also, it uses a new create_piece() factory to create each piece.

An alternative CheckersBoard.populate_board() implementation is provided in gameboard4.py (not shown)—this version uses a subtle combination of a list comprehension and a couple of itertools functions.

class AbstractBoard:

    __classForPiece = {(DRAUGHT, BLACK): BlackDraught,
            (PAWN, BLACK): BlackChessPawn,
            ...
            (QUEEN, WHITE): WhiteChessQueen}
    ...
    def create_piece(self, kind, color):
        return AbstractBoard.__classForPiece[kind, color]()

This version of the create_piece() factory (also from gameboard3.py, of course) is a method of the AbstractBoard that the CheckersBoard and ChessBoard classes inherit. It takes two constants and looks them up in a static (i.e., class-level) dictionary whose keys are (piece kind, color) 2-tuples, and whose values are class objects. The looked-up value—a class—is immediately called (using the () call operator), and the resulting piece instance is returned.

The classes in the dictionary could have been individually coded (as they were in gameboard1.py) or created dynamically but riskily (as they were in gameboard2.py). But for gameboard3.py, we have created them dynamically and safely, without using eval() or exec().

for code in itertools.chain((0x26C0, 0x26C2), range(0x2654, 0x2660)):
    char = chr(code)
    name = unicodedata.name(char).title().replace(" ", "")
    if name.endswith("sMan"):
        name = name[:-4]
    new = make_new_method(char)
    Class = type(name, (Piece,), dict(__slots__=(), __new__=new))
    setattr(sys.modules[__name__], name, Class) # Can be done better!

This code has the same overall structure as the code shown earlier for creating the fourteen piece subclasses that the program needs (21 left-arrow.jpg). Only this time instead of using eval() and exec() we take a somewhat safer approach.

Once we have the character and name we create a new function (called new()) by calling a custom make_new_method() function. We then create a new class using the built-in type() function. To create a class this way we must pass in the type’s name, a tuple of its base classes (in this case, there’s just one, Piece), and a dictionary of the class’s attributes. Here, we have set the __slots__ attribute to an empty tuple (to stop the class’s instances having a private __dict__ that isn’t needed), and set the __new__ method attribute to the new() function we have just created.

Finally, we use the built-in setattr() function to add to the current module (sys.modules[__name__]) the newly created class (Class) as an attribute called name (e.g., "WhiteChessPawn"). In gameboard4.py, we have written the last line of this code snippet in a nicer way:

    globals()[name] = Class

Here, we have retrieved a reference to the dict of globals and added a new item whose key is the name held in name, and whose value is our newly created Class. This does exactly the same thing as the setattr() line used in gameboard3.py.

def make_new_method(char): # Needed to create a fresh method each time
    def new(Class): # Can't use super() or super(Piece, Class)
        return Piece.__new__(Class, char)
    return new

This function is used to create a new() function (that will become a class’s __new__() method). We cannot use a super() call since at the time the new() function is created there is no class context for the super() function to access. Note that the Piece class (19 left-arrow.jpg) doesn’t have a __new__() method—but its base class (str) does, so that is the method that will actually be called.

Incidentally, the earlier code block’s new = make_new_method(char) line and the make_new_method() function just shown could both be deleted, so long as the line that called the make_new_method() function was replaced with these:

    new = (lambda char: lambda Class: Piece.__new__(Class, char))(char)
    new.__name__ = "__new__"

Here, we create a function that creates a function and immediately calls the outer function parameterized by char to return a new() function. (This code is used in gameboard4.py.)

All lambda functions are called "lambda", which isn’t very helpful for debugging. So, here, we explicitly give the function the name it should have, once it is created.

    def populate_board(self):
        for row, color in ((0, BLACK), (7, WHITE)):
            for columns, kind in (((0, 7), ROOK), ((1, 6), KNIGHT),
                    ((2, 5), BISHOP), ((3,), QUEEN), ((4,), KING)):
                for column in columns:
                    self.board[row][column] = self.create_piece(kind,
                            color)
        for column in range(8):
            for row, color in ((1, BLACK), (6, WHITE)):
                self.board[row][column] = self.create_piece(PAWN, color)

For completeness, here is the ChessBoard.populate_board() method from game-board3.py (and gameboard4.py). It depends on color and piece constants (which could be provided by a file or come from menu options, rather than being hard-coded). In the gameboard3.py version, this uses the create_piece() factory function shown earlier (22 left-arrow.jpg). But for gameboard4.py, we have used our final create_piece() variant.

def create_piece(kind, color):
    color = "White" if color == WHITE else "Black"
    name = {DRAUGHT: "Draught", PAWN: "ChessPawn", ROOK: "ChessRook",
            KNIGHT: "ChessKnight", BISHOP: "ChessBishop",
            KING: "ChessKing", QUEEN: "ChessQueen"}[kind]
    return globals()[color + name]()

This is the gameboard4.py version’s create_piece() factory function. It uses the same constants as gameboard3.py, but rather than keeping a dictionary of class objects it dynamically finds the relevant class in the dictionary returned by the built-in globals() function. The looked-up class object is immediately called and the resulting piece instance is returned.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020