Reader small image

You're reading from  Advanced Python Programming - Second Edition

Product typeBook
Published inMar 2022
PublisherPackt
ISBN-139781801814010
Edition2nd Edition
Right arrow
Author (1)
Quan Nguyen
Quan Nguyen
author image
Quan Nguyen

Quan Nguyen is a Python programmer and machine learning enthusiast. He is interested in solving decision-making problems under uncertainty. Quan has authored several books on Python programming and scientific computing. He is currently pursuing a Ph.D. degree in computer science at Washington University in St. Louis, researching Bayesian methods in machine learning.
Read more about Quan Nguyen

Right arrow

Chapter 17: The Builder Pattern

In the previous chapter, we covered the first two creational patterns—the factory method and abstract factory, both of which offer approaches to improve the way we create objects in nontrivial cases. The builder design pattern, on the other hand, as we'll discuss in this chapter, is useful for managing objects that consist of multiple parts that need to be implemented sequentially. By decoupling the construction of an object and its representation, the builder pattern allows us to reuse a construction multiple times.

Just as with the previous chapter, we will discuss real-life applications that use this design pattern as well as implementing a hands-on example ourselves.

In this chapter, we will discuss the following topics:

  • Understanding the builder pattern
  • Real-world examples
  • Use cases
  • Implementing an ordering application

By the end of the chapter, we will understand how to use the builder pattern and its...

Technical requirements

The code files for this chapter can be accessed through this link:

https://github.com/PacktPublishing/Advanced-Python-Programming-Second-Edition/tree/main/Chapter17

Understanding the builder pattern

Imagine that we want to create an object that is composed of multiple parts and the composition needs to be done step by step. The object is not complete unless all its parts are fully created. That's where the builder-design pattern can help us. The builder pattern separates the construction of a complex object from its representation. By keeping the construction separate from the representation, the same construction can be used to create several different representations (j.mp/builderpat).

A practical example can help us understand what the purpose of the builder pattern is. Suppose that we want to create a HyperText Markup Language (HTML) page generator. The basic structure (construction part) of an HTML page is always the same: it begins with <html> and finishes with </html>; inside the HTML section are the <head> and </head> elements; inside the head section are the <title> and </title> elements; and...

Real-world examples

In our everyday life, the builder design pattern is used in fast-food restaurants. The same procedure is always used to prepare a burger and the packaging (box and paper bag), even if there are many different kinds of burgers (classic, cheeseburger, and more) and different packages (small-sized box, medium-sized box, and so forth). The difference between a classic burger and a cheeseburger is in the representation, and not in the construction procedure. In this case, the director is the cashier who gives the crew instructions about what needs to be prepared, and the builder is the person from the crew that takes care of a specific order.

We can also find software examples, as follows:

  • The HTML example that was mentioned at the beginning of the chapter is actually used by django-widgy (https://wid.gy/), a third-party tree editor for Django that can be used as a content management system (CMS). The django-widgy editor contains a page builder that can be...

Use cases

We use the builder pattern when we know that an object must be created in multiple steps, and different representations of the same construction are required. These requirements exist in many applications, such as page generators (for example, the HTML page generator mentioned in this chapter), document converters, and user interface (UI) form creators (j.mp/pipbuild).

Some online resources mention that the builder pattern can also be used as a solution to the telescopic constructor problem. The telescopic constructor problem occurs when we are forced to create a new constructor for supporting different ways of creating an object. The problem is that we end up with many constructors and long parameter lists that are hard to manage. An example of the telescopic constructor is listed on the Stack Overflow website (j.mp/sobuilder). Fortunately, this problem does not exist in Python, because it can be solved in at least two ways, as outlined here:

  • With named parameters...

Implementing an ordering application

Let's see how we can use the builder design pattern to make a pizza-ordering application. The pizza example is particularly interesting because a pizza is prepared in steps that should follow a specific order. To add the sauce, you first need to prepare the dough. To add the topping, you first need to add the sauce. And you can't start baking the pizza unless both the sauce and the topping are placed on the dough. Moreover, each pizza usually requires a different baking time, depending on the thickness of its dough and the topping used.

We start by importing the required modules and declaring a few Enum parameters (j.mp/pytenum) plus a constant that is used many times in the application. The STEP_DELAY constant is used to add a time delay between the different steps of preparing a pizza (prepare the dough, add the sauce, and so on), as follows:

from enum import Enum
import time
PizzaProgress = Enum('PizzaProgress', &apos...

Summary

In this chapter, we have seen how to use the builder design pattern. We use the builder pattern for creating an object in situations where using the factory pattern (either a factory method or an abstract factory) is not a good option. The builder pattern is usually a better candidate than the factory pattern when we want to create a complex object, when different representations of an object are required, or when we want to create an object at one point in time but access it at a later point.

We saw how the builder pattern is used in fast-food restaurants for preparing meals, and how two third-party Django packages, django-widgy and django-query-builder, use it for generating HTML pages and dynamic SQL queries, respectively. We focused on the differences between the builder pattern and the factory pattern and provided a preconfigured (factory) and customer (builder) computer order analogy to clarify them. We also looked at how to create a pizza-ordering application with...

Questions

  1. What are the high-level applications of the builder pattern?
  2. What are some common computer applications that require or benefit from the builder pattern?
  3. How does the builder pattern create an object and how is that process different from what the factory pattern does?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Advanced Python Programming - Second Edition
Published in: Mar 2022Publisher: PacktISBN-13: 9781801814010
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Quan Nguyen

Quan Nguyen is a Python programmer and machine learning enthusiast. He is interested in solving decision-making problems under uncertainty. Quan has authored several books on Python programming and scientific computing. He is currently pursuing a Ph.D. degree in computer science at Washington University in St. Louis, researching Bayesian methods in machine learning.
Read more about Quan Nguyen