Mastering Python Design Patterns Create various design patterns to master the art of solving problems using Python pdf pdf (2022)

Table of Contents
Mastering Python Design Patterns Create various design patterns to master the art of solving problems using Python Sakis Kasampalis Mastering Python Design Patterns Credits About the Author Sakis Kasampalis About the Reviewers Evan Dempsey Amitabh Sharma Yogendra Sharma Patrycja Szabłowska www.PacktPub.com Support files, eBooks, discount offers, and more Why subscribe? Free access for Packt account holders Table of Contents Preface 1 Chapter 1: The Factory Pattern 9 Chapter 2: The Builder Pattern 29 Chapter 3: The Prototype Pattern 45 Chapter 4: The Adapter Pattern 57 Chapter 5: The Decorator Pattern 65 Chapter 6: The Facade Pattern 75 Chapter 7: The Flyweight Pattern 85 Chapter 8: The Model-View-Controller Pattern 93 Chapter 9: The Proxy Pattern 103 Chapter 10: The Chain of Responsibility Pattern 113 Chapter 11: The Command Pattern 125 Chapter 12: The Interpreter Pattern 137 Chapter 13: The Observer Pattern 149 Chapter 14: The State Pattern 159 Chapter 15: The Strategy Pattern 171 Chapter 16: The Template Pattern 181 Preface Design patterns Common misunderstandings about design patterns Design patterns and Python What this book covers What you need for this book Who this book is for Conventions Reader feedback Customer support Downloading the example code Errata Piracy Questions The Factory Pattern Factory Method A real-life example A software example Use cases Implementation Abstract Factory A real-life example A software example Use cases Implementation Summary The Builder Pattern A real-life example A software example Use cases Implementation Summary Videos

(1)

(2)

Mastering Python Design

Patterns

Create various design patterns to master the art of

solving problems using Python

Sakis Kasampalis

BIRMINGHAM - MUMBAI

(3)

Mastering Python Design Patterns

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: January 2015

Production reference: 1220115

Published by Packt Publishing Ltd.Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-932-4

www.packtpub.com

(4)

Credits

Author

Sakis Kasampalis

ReviewersEvan Dempsey

Amitabh Sharma

Yogendra Sharma

Patrycja Szabłowska

Commissioning EditorKunal Parikh

Acquisition EditorOwen Roberts

Content Development EditorSumeet Sawant

Technical EditorsTanvi Bhatt

Gaurav Suri

Copy EditorsShivangi Chaturvedi

Nithya P.

Adithi Shetty

Project CoordinatorAboli Ambardekar

ProofreadersAmeesha Green

Joyce Littlejohn

IndexerTejal Soni

GraphicsAbhinash Sahu

Production CoordinatorAparna Bhagat

Cover WorkAparna Bhagat

(5)

About the Author

Sakis Kasampalis

(@SKasampalis) is a software engineer living in the

Netherlands. He is not dogmatic about particular programming languages and tools; his principle is that the right tool should be used for the right job. One of his favorite

tools is Python because he finds it very productive.

Sakis was also the technical reviewer of Mastering Object-oriented Python and Learning Python Design Patterns, published by Packt Publishing.

I want to thank my sweetheart, Georgia, for supporting this effort. Many thanks to Owen Roberts who encouraged me to write this book. I also want to thank Sumeet Sawant for being a very kind and cooperative content development editor. Last but not least, I want to thank the reviewers of this book for their valuable feedback.

(6)

About the Reviewers

Evan Dempsey

is a software developer from Waterford, Ireland. When he isn't

hacking in Python for fun and profit, he enjoys craft beers, common Lisp, and

keeping up with modern research in machine learning. He is a contributor to several open source projects.

Amitabh Sharma

is a professional software engineer. He has worked extensively on enterprise applications in telecommunications and business analytics. His work is focused on service-oriented architecture, data warehouses, and languages such as Java, Python, and others.

I would like to thank my grandfather and my father for allowing me to learn all that I can. I would also like to thank my wife, Komal, for her support and encouragement.

(7)

Yogendra Sharma

was born and brought up in a small but cultural town, Pratapgarh, in the state of Rajasthan. His basic education has been imparted in his hometown itself, and he completed his BTech in Computer Science from Jaipur. He is basically an engineer by heart and a technical enthusiast by nature.

He has vast experience in the fields of Python, Django framework, web app security,

networking, Web 2.0, and C++.

Along with CCNA, many other esteemed certifications have been awarded to him.

He is an active member of International Association of Engineers, Ubuntu, India, and Computer Society of India.

More recently, he participated in bug bounty programs and won many bug bounties, including the respected Yahoo, Ebay, PayPal bug bounty. He has been appointed as security researcher for several respected organizations, such as Adobe, Ebay, Avira, Moodle, Cisco, Atlassian, Basecamp, CodeClimate, Abacus, Rediff, Assembla, RecruiterBox, Tumbler, Wrike, Indeed, HybridSaaS, Sengrid, and SnapEngag.

He has reviewed many books from reputed publishing houses. You can find him on

LinkedIn at http://in.linkedin.com/in/yogendra0sharma.

I would like to thank all my friends who always encouraged me to do something new and believing in me.

Patrycja Szabłowska

is a Python developer with some Java background, with experience mainly in backend development. She graduated from Nicolaus

Copernicus University in Toruń, Poland.

She is currently working in Warsaw, Poland, at Grupa Wirtualna Polska. She is constantly exploring technical novelties and is open-minded and eager to learn about the next Python library or framework. Her favorite programming motto is Code is read much more often than it is written.

I'd like to thank my husband, Wacław, for encouraging me to explore new frontiers,

and also my parents for teaching me what matters the most.

(8)

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital

book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

• Fully searchable across every book published by Packt

• Copy and paste, print, and bookmark content

• On demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

(9)

(10)

Table of Contents

Preface 1

Chapter 1: The Factory Pattern

9

Factory Method 9

A real-life example 10

A software example 10

Use cases 10

Implementation 12

Abstract Factory 20

A real-life example 20

A software example 21

Use cases 21

Implementation 21

Summary 27

Chapter 2:

The Builder Pattern

29

A real-life example 30

A software example 30

Use cases 31

Implementation 34Summary 43

Chapter 3: The Prototype Pattern

45

A real-life example 47

A software example 48

Use cases 48

Implementation 49Summary 54

(11)

Table of Contents

[ ii ]

Chapter 4: The Adapter Pattern

57

A real-life example 58

A software example 58

Use cases 59

Implementation 59Summary 63

Chapter 5: The Decorator Pattern

65

A real-life example 66

A software example 67

Use cases 67

Implementation 68Summary 73

Chapter 6: The Facade Pattern

75

A real-life example 76

A software example 76

Use cases 77

Implementation 77Summary 83

Chapter 7: The Flyweight Pattern

85

A real-life example 86

A software example 86

Use cases 86

Implementation 87Summary 92

Chapter 8: The Model-View-Controller Pattern

93

A real-life example 94

A software example 94

Use cases 95

Implementation 96Summary 100

Chapter 9: The Proxy Pattern

103

A real-life example 106

A software example 107

Use cases 107

(12)

Table of Contents

[ iii ]

Chapter 10: The Chain of Responsibility Pattern

113

A real-life example 115

A software example 115

Use cases 116

Implementation 117Summary 122

Chapter 11: The Command Pattern

125

A real-life example 126

A software example 126

Use cases 127

Implementation 127Summary 135

Chapter 12: The Interpreter Pattern

137

A real-life example 138

A software example 138

Use cases 139

Implementation 140Summary 147

Chapter 13: The Observer Pattern

149

A real-life example 149

A software example 150

Use cases 151

Implementation 151Summary 158

Chapter 14: The State Pattern

159

A real-life example 161

A software example 162

Use cases 162

Implementation 162Summary 169

Chapter 15: The Strategy Pattern

171

A real-life example 172

A software example 173

Use cases 174

(Video) Design Patterns in Plain English | Mosh Hamedani

(13)

Table of Contents

[ iv ]

Chapter 16: The Template Pattern

181

A real-life example 187

A software example 188

Use cases 188

Implementation 189Summary 192

(14)

Preface

Design patterns

In software engineering, a design pattern is a recommended solution to a software

design problem. Design patterns generally describe how to structure our code to

solve common design problems using best practices. It is important to note that a design pattern is a high-level solution; it doesn't focus on implementation details such as algorithms and data structures [GOF95, page 13], [j.mp/srcmdp]. It is up to us, as software engineers, to decide which algorithm and data structure is optimal to use for the problem we are trying to solve.

If you are wondering what is the meaning of the text within [], please jump to the Conventions section of this preface for a moment to see how references are formatted in this book.

The most important part of a design pattern is probably its name. The benefit

of naming all patterns is that we have, on our hands, a common vocabulary to communicate [GOF95, page 13]. Thus, if you send some code for review and your peer reviewer gives feedback mentioning "I think that you can use a Strategy here instead of ...", even if you don't know or remember what a strategy is, you can immediately look it up.

(15)

Preface

[ 2 ]

Common misunderstandings about

design patterns

There are a few misunderstandings about design patterns. One misunderstanding is that design patterns should be used right from the start when writing code. It is not unusual to see developers struggling with which pattern they should use in

their code, even if they haven't first tried to solve the problem in their own way

[j.mp/prsedp], [j.mp/stedp].

Not only is this wrong, but it is also against the nature of design patterns. Design

patterns are discovered (in contrast to invented) as better solutions over existing solutions. If you have no existing solution, it doesn't make sense to look for a better one. Just go ahead and use your skills to solve your problem as best as you think. If your code reviewers have no objections and through time you see that your solution

is smart and flexible enough, it means that you don't need to waste your time on

struggling about which pattern to use. You might have even discovered a better

design pattern than the existing one. Who knows? The point is do not limit your

creativity in favor of forcing yourself to use existing design patterns.

A second misunderstanding is that design patterns should be used everywhere. This results in creating complex solutions with unnecessary interfaces and hierarchies,

where a simpler and straightforward solution would be sufficient. Do no treat design

patterns as a panacea because they are not. They must be used only if there is proof that your existing code "smells", and is hard to extend and maintain. Try thinking in terms of you aren't gonna need it (YAGNI [j.mp/c2yagni]) and Keep it simple stupid(KISS [j.mp/wikikis]). Using design patterns everywhere is as evil as premature optimization [j.mp/c2pro].

Design patterns and Python

This book focuses on design patterns in Python. Python is different than most common programming languages used in popular design patterns books (usually

Java [FFBS04] or C++ [GOF95]). It supports duck-typing, functions are first-class

(16)

Preface

[ 3 ]

What this book covers

Part 1: Creational patterns presents design patterns that deal with object creation.

Chapter 1, The Factory Pattern, will teach you how to use the Factory design pattern

(Factory Method and Abstract Factory) to initialize objects, and cover the benefits of

using the Factory design pattern instead of direct object instantiation.

Chapter 2, The Builder Pattern, will teach you how to simplify the creation of objects that are typically composed by more than one related objects.

Chapter 3, The Prototype Pattern, will teach you how to create a new object that is a full copy (hence, the name clone) of an existing object.

Part 2: Structural patterns presents design patterns that deal with relationships between the entities (classes, objects, and so on) of a system.

Chapter 4, The Adapter Pattern, will teach you how to make your existing code compatible with a foreign interface (for example, an external library) with minimal changes.

Chapter 5, The Decorator Pattern, will teach you how to enhance the functionality of an object without using inheritance.

Chapter 6, The Facade Pattern, will teach you how to create a single entry point to hide the complexity of a system.

Chapter 7, The Flyweight Pattern, will teach you how to reuse objects from an object pool to improve the memory usage and possibly the performance of your applications.

Chapter 8, The Model-View-Controller Pattern, will teach you how to improve the maintainability of your applications by avoiding mixing the business logic with the user interface.

Chapter 9, The Proxy Pattern, will teach you how to improve the security of your application by adding an extra layer of protection.

Part 3: Behavioral patterns presents design patterns that deal with the communication of the system's entities.

(17)

Preface

[ 4 ]

Chapter 11, The Command Pattern, will teach you how to make your application capable of reverting already applied operations.

Chapter 12, The Interpreter Pattern, will teach you how to create a simple language on top of Python, which can be used by domain experts without forcing them to learn how to program in Python.

Chapter 13, The Observer Pattern, will teach you how to send notifications to the registered stakeholders of an object whenever its state changes.

Chapter 14, The State Pattern, will teach you how to create a state machine to model

a problem and the benefits of this technique.

Chapter 15, The Strategy Pattern, will teach you how to pick (during runtime) an algorithm between many available algorithms, based on some input criteria (for example, the element size).

Chapter 16, The Template Pattern, will teach you how to make a clear separation between the common and different parts of an algorithm to avoid unnecessary code duplication.

What you need for this book

The code is written exclusively in Python 3. Python 3 is, in many aspects, not compatible with Python 2.x [j.mp/p2orp3]. The focus is on Python 3.4.0 but using

Python 3.3.0 should also be fine, since there are no syntax differences between

Python 3.3.0 and Python 3.4.0 [j.mp/py3dot4]. In general, if you install the latest Python 3 version from www.python.org, you should be fine with running the examples. Most modules/libraries that are used in the examples are a part of the Python 3 distribution. If an example requires any extra modules to be installed, instructions on how to install them are given before presenting the related code.

Who this book is for

The audience of this book is Python programmers with an intermediate background and an interest in design patterns implemented in idiomatic Python. Programmers

of other languages who are interested in Python can also benefit, but it's better if they first read some materials that explain how things are done in Python

(18)

Preface

[ 5 ]

Conventions

In this book, you will find a number of text styles that distinguish between different

kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,

pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We will use two libraries that are part of the Python distribution for working with XML and JSON: xml.etree.ElementTree and json."

A block of code is set as follows:

@property

def parsed_data(self): return self.data

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

@property

def parsed_data(self): return self.data

Any command-line input or output is written as follows:

>>> python3 factory_method.py

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Warnings or important notes appear in a box like this.

(19)

Preface

[ 6 ]

Book references follow the format [Author, page]. For example, the reference [GOF95, page 10] refers to the 10th page of the GOF (Design Patterns: Elements of Reusable Object-Oriented Software) book. At the end of the book, there is a section devoted to all book references.

Web references follow the format [j.mp/shortened]. These are shortened URL addresses that you can type or copy/paste into your web browser and be redirected to the real (usually longer and sometimes uglier) web reference. For example, typing j.mp/idiompyt in you web browser's address bar should redirect you to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support

(20)

Preface

[ 7 ]

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes

do happen. If you find a mistake in one of our books—maybe a mistake in the text or

the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this

book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm

link, and entering the details of your errata. Once your errata are verified, your

submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.

(21)

(22)

The Factory Pattern

Creational design patterns deal with an object creation [j.mp/wikicrea]. The aim of a creational design pattern is to provide better alternatives for situations where a direct object creation (which in Python happens by the __init__() function [j.mp/divefunc], [Lott14, page 26]) is not convenient.

In the Factory design pattern, a client asks for an object without knowing where the object is coming from (that is, which class is used to generate it). The idea behind a factory is to simplify an object creation. It is easier to track which objects are created if this is done through a central function, in contrast to letting a client create objects using a direct class instantiation [Eckel08, page 187]. A factory reduces the complexity of maintaining an application by decoupling the code that creates an object from the code that uses it [Zlobin13, page 30].

Factories typically come in two forms: the Factory Method, which is a method (or in Pythonic terms, a function) that returns a different object per input parameter [j.mp/factorympat]; the Abstract Factory, which is a group of Factory Methods used to create a family of related products [GOF95, page 100], [j.mp/absfpat].

Factory Method

(23)

The Factory Pattern

[ 10 ]

A real-life example

An example of the Factory Method pattern used in reality is in plastic toy construction. The molding powder used to construct plastic toys is the same,

but different figures can be produced using different plastic molds. This is like having a Factory Method in which the input is the name of the figure that we want (duck and car) and the output is the plastic figure that we requested.

The toy construction case is shown in the following figure, which is provided by www.sourcemaking.com [j.mp/factorympat].

A software example

The Django framework uses the Factory Method pattern for creating the fields

of a form. The forms module of Django supports the creation of different kinds

of fields (CharField, EmailField) and customizations (max_length, required) [j.mp/djangofacm].

Use cases

If you realize that you cannot track the objects created by your application because the code that creates them is in many different places instead of a single function/method, you should consider using the Factory Method pattern [Eckel08, page 187]. The Factory Method centralizes an object creation and tracking your objects becomes

much easier. Note that it is absolutely fine to create more than one Factory Method,

(24)

Chapter 1

[ 11 ]

The Factory Method is also useful when you want to decouple an object creation

from an object usage. We are not coupled/bound to a specific class when creating an

object, we just provide partial information about what we want by calling a function. This means that introducing changes to the function is easy without requiring any changes to the code that uses it [Zlobin13, page 30].

Another use case worth mentioning is related to improving the performance and memory usage of an application. A Factory Method can improve the performance and memory usage by creating new objects only if it is absolutely necessary [Zlobin13, page 28]. When we create objects using a direct class instantiation, extra memory is allocated every time a new object is created (unless the class uses caching internally, which is usually not the case). We can see that in practice in the following

code (file id.py), it creates two instances of the same class A and uses the id()function to compare their memory addresses. The addresses are also printed in the output so that we can inspect them. The fact that the memory addresses are different means that two distinct objects are created as follows:

class A(object): pass

if __name__ == '__main__': a = A()

b = A()

print(id(a) == id(b)) print(a, b)

Executing id.py on my computer gives the following output:

>> python3 id.py False

<__main__.A object at 0x7f5771de8f60> <__main__.A object at 0x7f5771df2208>

Note that the addresses that you see if you execute the file are not the same as I see

because they depend on the current memory layout and allocation. But the result must be the same: the two addresses should be different. There's one exception that happens if you write and execute the code in the Python Read-Eval-Print Loop

(25)

The Factory Pattern

[ 12 ]

Implementation

Data comes in many forms. There are two main file categories for storing/retrieving data: human-readable files and binary files. Examples of human-readable files are XML, Atom, YAML, and JSON. Examples of binary files are the .sq3 file format used by SQLite and the .mp3 file format used to listen to music.

In this example, we will focus on two popular human-readable formats: XML and

JSON. Although human-readable files are generally slower to parse than binary files, they make data exchange, inspection, and modification much easier. For this reason, it is advised to prefer working with human-readable files, unless there are other

restrictions that do not allow it (mainly unacceptable performance and proprietary binary formats).

In this problem, we have some input data stored in an XML and a JSON file, and we

want to parse them and retrieve some information. At the same time, we want to centralize the client's connection to those (and all future) external services. We will use the Factory Method to solve this problem. The example focuses only on XML and JSON, but adding support for more services should be straightforward.

First, let's take a look at the data files. The XML file, person.xml, is based on the Wikipedia example [j.mp/wikijson] and contains information about individuals (firstName, lastName, gender, and so on) as follows:

(Video) 10 Architecture Patterns Used In Enterprise Software Development Today

<streetAddress>21 2nd Street</streetAddress> <city>New York</city>

<state>NY</state>

<postalCode>10021</postalCode> </address>

<phoneNumbers>

(26)

Chapter 1

[ 13 ]

<lastName>Liar</lastName> <age>19</age>

<address>

<streetAddress>18 2nd Street</streetAddress> <city>New York</city>

<state>NY</state>

<postalCode>10021</postalCode> </address>

<phoneNumbers>

<phoneNumber type="home">212 555-1234</phoneNumber> </phoneNumbers>

<streetAddress>18 2nd Street</streetAddress> <city>New York</city>

<state>NY</state>

<postalCode>10021</postalCode> </address>

<phoneNumbers>

<phoneNumber type="home">212 555-1234</phoneNumber> <phoneNumber type="mobile">001 452-8819</phoneNumber> </phoneNumbers>

<gender>

<type>female</type> </gender>

</person></persons>

The JSON file, donut.json, comes from the GitHub account of Adobe [j.mp/

(27)

The Factory Pattern

{ "id": "5007", "type": "Powdered Sugar" },

{ "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5003", "type": "Chocolate" }, "name": "Raised", "ppu": 0.55,

"name": "Old Fashioned", "ppu": 0.55,

(28)

Chapter 1

[ 15 ]

{ "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" } ]

},

"topping": [

{ "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ]

}]

We will use two libraries that are part of the Python distribution for working with XML and JSON: xml.etree.ElementTree and json as follows:

import xml.etree.ElementTree as etreeimport json

The JSONConnector class parses the JSON file and has a parsed_data() method that returns all data as a dictionary (dict). The property decorator is used to make parsed_data() appear as a normal variable instead of a method as follows:

class JSONConnector:

def __init__(self, filepath): self.data = dict()

with open(filepath, mode='r', encoding='utf-8') as f: self.data = json.load(f)

@property

def parsed_data(self): return self.data

The XMLConnector class parses the XML file and has a parsed_data() method that returns all data as a list of xml.etree.Element as follows:

class XMLConnector:

def __init__(self, filepath):

self.tree = etree.parse(filepath) @property

(29)

The Factory Pattern

[ 16 ]

The connection_factory() function is a Factory Method. It returns an instance of JSONConnector or XMLConnector depending on the extension of the input file path as follows:

def connection_factory(filepath): if filepath.endswith('json'): connector = JSONConnector elif filepath.endswith('xml'): connector = XMLConnector else:

raise ValueError('Cannot connect to {}'.format(filepath)) return connector(filepath)

The connect_to() function is a wrapper of connection_factory(). It adds exception handling as follows:

def connect_to(filepath): factory = None

try:

factory = connection_factory(filepath) except ValueError as ve:

print(ve) return factory

The main() function demonstrates how the Factory Method design pattern can be

used. The first part makes sure that exception handling is effective as follows:

def main():

sqlite_factory = connect_to('data/person.sq3')

The next part shows how to work with the XML files using the Factory Method.

XPath is used to find all person elements that have the last name Liar. For each matched person, the basic name and phone number information are shown as follows:

xml_factory = connect_to('data/person.xml') xml_data = xml_factory.parsed_data()

liars = xml_data.findall

(".//{person}[{lastName}='{}']".format('Liar')) print('found: {} persons'.format(len(liars))) for liar in liars:

print('first name:

{}'.format(liar.find('firstName').text))

(30)

Chapter 1

[ 17 ]

The final part shows how to work with the JSON files using the Factory Method.

Here, there's no pattern matching, and therefore the name, price, and topping of all donuts are shown as follows:

json_factory = connect_to('data/donut.json') json_data = json_factory.parsed_data

print('found: {} donuts'.format(len(json_data))) for donut in json_data:

print('name: {}'.format(donut['name'])) print('price: ${}'.format(donut['ppu']))

[print('topping: {} {}'.format(t['id'], t['type'])) for t in donut['topping']]

For completeness, here is the complete code of the Factory Method implementation (factory_method.py) as follows:

import xml.etree.ElementTree as etreeimport json

class JSONConnector:

def __init__(self, filepath): self.data = dict()

with open(filepath, mode='r', encoding='utf-8') as f: self.data = json.load(f)

@property

def parsed_data(self): return self.dataclass XMLConnector:

def __init__(self, filepath):

self.tree = etree.parse(filepath) @property

def parsed_data(self): return self.tree

def connection_factory(filepath): if filepath.endswith('json'): connector = JSONConnector elif filepath.endswith('xml'): connector = XMLConnector else:

raise ValueError('Cannot connect to {}'.format(filepath)) return connector(filepath)

(31)

The Factory Pattern

[ 18 ]

def connect_to(filepath): factory = None

try:

factory = connection_factory(filepath) except ValueError as ve:

print(ve) return factorydef main():

sqlite_factory = connect_to('data/person.sq3') print()

xml_factory = connect_to('data/person.xml') xml_data = xml_factory.parsed_data

liars = xml_data.findall(".//{}[{}='{}']".format('person', 'lastName', 'Liar'))

print('found: {} persons'.format(len(liars))) for liar in liars:

print('first name:

{}'.format(liar.find('firstName').text))

print('last name: {}'.format(liar.find('lastName').text)) [print('phone number ({}):'.format(p.attrib['type']), p.text) for p in liar.find('phoneNumbers')]

print()

json_factory = connect_to('data/donut.json') json_data = json_factory.parsed_data

print('found: {} donuts'.format(len(json_data))) for donut in json_data:

print('name: {}'.format(donut['name'])) print('price: ${}'.format(donut['ppu']))

[print('topping: {} {}'.format(t['id'], t['type'])) for t in donut['topping']]

if __name__ == '__main__': main()

Here is the output of this program as follows:

>>> python3 factory_method.pyCannot connect to data/person.sq3

(32)

Chapter 1

Notice that although JSONConnector and XMLConnector have the same interfaces, what is returned by parsed_data() is not handled in a uniform way. Different python code must be used to work with each connector. Although it would be nice to be able to use the same code for all connectors, this is at most times not realistic unless we use some kind of common mapping for the data which is very often provided by external data providers. Assuming that you can use exactly the same

(33)

The Factory Pattern

[ 20 ]

As it is now, the code does not forbid a direct instantiation of a connector. Is it

possible to do this? Try doing it.

Hint: Functions in Python can have nested classes.

Abstract Factory

The Abstract Factory design pattern is a generalization of Factory Method. Basically, an Abstract Factory is a (logical) group of Factory Methods, where each Factory Method is responsible for generating a different kind of object [Eckel08, page 193].

A real-life example

Abstract Factory is used in car manufacturing. The same machinery is used for stamping the parts (doors, panels, hoods, fenders, and mirrors) of different car

models. The model that is assembled by the machinery is configurable and easy

to change at any time. We can see an example of the car manufacturing Abstract

(34)

Chapter 1

[ 21 ]

A software example

The django_factory package is an Abstract Factory implementation for creating

Django models in tests. It is used for creating instances of models that support test-specific attributes. This is important because the tests become readable and avoid

sharing unnecessary code [j.mp/djangoabs].

Use cases

Since the Abstract Factory pattern is a generalization of the Factory Method pattern,

it offers the same benefits: it makes tracking an object creation easier, it decouples

an object creation from an object usage, and it gives us the potential to improve the memory usage and performance of our application.

But a question is raised: how do we know when to use the Factory Method versus

using an Abstract Factory? The answer is that we usually start with the Factory Method which is simpler. If we find out that our application requires many Factory

Methods which it makes sense to combine for creating a family of objects, we end up with an Abstract Factory.

A benefit of the Abstract Factory that is usually not very visible from a user's point of view when using the Factory Method is that it gives us the ability to modify the behavior of our application dynamically (in runtime) by changing the active Factory Method. The classic example is giving the ability to change the look and feel of an application (for example, Apple-like, Windows-like, and so on) for the user while the application is in use, without the need to terminate it and start it again [GOF95, page 99].

Implementation

(35)

The Factory Pattern

[ 22 ]

Let's start with the kid's game. It is called FrogWorld. The main hero is a frog who enjoys eating bugs. Every hero needs a good name, and in our case the name is given by the user in runtime. The interact_with() method is used to describe the interaction of the frog with an obstacle (for example, bug, puzzle, and other frog) as follows:

class Frog:

def __init__(self, name): self.name = name def __str__(self): return self.name

def interact_with(self, obstacle):

print('{} the Frog encounters {} and {}!'.format(self, obstacle, obstacle.action()))

There can be many different kinds of obstacles but for our example an obstacle can only be a Bug. When the frog encounters a bug, only one action is supported: it eats it!

class Bug:

(Video) 6 Design Patterns Every Android Developer Must Know

def __str__(self): return 'a bug' def action(self): return 'eats it'

The FrogWorld class is an Abstract Factory. Its main responsibilities are creating the main character and the obstacle(s) of the game. Keeping the creation methods separate and their names generic (for example, make_character(), make_

obstacle()) allows us to dynamically change the active factory (and therefore the active game) without any code changes. In a statically typed language, the Abstract Factory would be an abstract class/interface with empty methods, but in Python this is not required because the types are checked in runtime [Eckel08, page 195], [j.mp/ginstromdp] as follows:

class FrogWorld:

def __init__(self, name): print(self)

self.player_name = name

def __str__(self):

(36)

Chapter 1

[ 23 ]

def make_character(self):

return Frog(self.player_name) def make_obstacle(self):

return Bug()

The WizardWorld game is similar. The only differences are that the wizard battles against monsters like orks instead of eating bugs!

class Wizard:

def __init__(self, name): self.name = name def __str__(self): return self.name

def interact_with(self, obstacle):

print('{} the Wizard battles against {} and {}!'.format(self, obstacle, obstacle.action()))class Ork:

def __str__(self): return 'an evil ork' def action(self):

return 'kills it'class WizardWorld:

def __init__(self, name): print(self)

self.player_name = name def __str__(self):

return '\n\n\t--- Wizard World ---' def make_character(self):

return Wizard(self.player_name) def make_obstacle(self):

(37)

The Factory Pattern

[ 24 ]

The GameEnvironment is the main entry point of our game. It accepts factory as an input, and uses it to create the world of the game. The play() method initiates the interaction between the created hero and the obstacle as follows:

class GameEnvironment:

def __init__(self, factory):

self.hero = factory.make_character() self.obstacle = factory.make_obstacle() def play(self):

self.hero.interact_with(self.obstacle)

The validate_age() function prompts the user to give a valid age. If the age is not

valid, it returns a tuple with the first element set to False. If the age is fine, the first element of the tuple is set to True and that's the case where we actually care about the second element of the tuple, which is the age given by the user as follows:

def validate_age(name):

Last but not least comes the main() function. It asks for the user's name and age, and decides which game should be played by the age of the user as follows:

def main(): environment = GameEnvironment(game(name)) environment.play()

And the complete code of the Abstract Factory implementation (abstract_factory.py) is given as follows:

class Frog:

(38)

Chapter 1

[ 25 ]

def __str__(self): return self.name

def interact_with(self, obstacle):

print('{} the Frog encounters {} and {}!'.format(self, obstacle, obstacle.action()))

class Bug:

def __str__(self): return 'a bug' def action(self): return 'eats it'class FrogWorld:

def __init__(self, name): print(self)

self.player_name = name

def __str__(self):

return '\n\n\t--- Frog World ---' def make_character(self):

return Frog(self.player_name) def make_obstacle(self):

return Bug()class Wizard:

def __init__(self, name): self.name = name def __str__(self): return self.name

def interact_with(self, obstacle):

print('{} the Wizard battles against {} and {}!'.format(self, obstacle, obstacle.action()))class Ork:

(39)

The Factory Pattern def make_character(self):

return Wizard(self.player_name) def make_obstacle(self):

return Ork()class GameEnvironment:

def __init__(self, factory):

self.hero = factory.make_character() self.obstacle = factory.make_obstacle() def play(self):

self.hero.interact_with(self.obstacle)def validate_age(name): environment = GameEnvironment(game(name)) environment.play()

(40)

Chapter 1

[ 27 ]A sample output of this program is as follows:

>>> python3 abstract_factory.pyHello. What's your name? NickWelcome Nick. How old are you? 17 --- Frog World

---Nick the Frog encounters a bug and eats it!

Try extending the game to make it more complete. You can go as far as you want: many obstacles, many enemies, and whatever else you like.

Summary

In this chapter, we have seen how to use the Factory Method and the Abstract Factory design patterns. Both patterns are used when we want to (a) track an object creation, (b) decouple an object creation from an object usage, or even (c) improve the performance and resource usage of an application. Case (c) was not demonstrated in the chapter. You might consider it as a good exercise.

The Factory Method design pattern is implemented as a single function that doesn't belong to any class, and is responsible for the creation of a single kind of object (a shape, a connection point, and so on). We saw how the Factory Method relates

to toy construction, mentioned how it is used by Django for creating different form fields, and discussed other possible use cases for it. As an example, we implemented a Factory Method that provides access to the XML and JSON files.

The Abstract Factory design pattern is implemented as a number of Factory Methods that belong to a single class and are used to create a family of related objects (the parts of a car, the environment of a game, and so forth). We mentioned how the

Abstract Factory is related with car manufacturing, how the django_factory Django

package makes use of it to create clean tests, and covered the use cases of it. The implementation of the Abstract Factory is a mini-game that shows how we can use many related factories in a single class.

In the next chapter, we will talk about the Builder pattern, which is another creational

pattern that can be used for fine-controlling the creation of complex objects.

(41)

(42)

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 [GOF95, page 110], [j.mp/builderpat].

A practical example can help us understand what the purpose of the Builder pattern is. Suppose that we want to create an 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 so forth. But the representation of the page can differ. Each page has its own title, its own headings, and different <body> contents. Moreover, the page is usually built in steps: one function adds the title, another adds the main heading, another the footer, and so on. Only after the whole structure of a page is complete can it be shown to

the client using a final render function. We can take it even further and extend the

HTML generator so that it can generate totally different HTML pages. One page might contain tables, another page might contain image galleries, yet another page contains the contact form, and so on.

(43)

The Builder Pattern

[ 30 ]

A real-life example

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. The director is the cashier who gives instructions about what needs to be prepared to the crew, and the builder is the person from the

crew that takes care of the specific order. The following figure provided by www.sourcemaking.com shows a Unified Modeling Language (UML) sequence diagram of the communication that takes place between the customer (client), the cashier (director), and the crew (builder) when a kid's menu is ordered [j.mp/builderpat].

A software example

The HTML example that was mentioned at the beginning of the chapter is actually used by django-widgy, 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 used for creating HTML pages with different layouts [j.mp/widgypb].

(44)

Chapter 2

[ 31 ]

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 (like the HTML page generator mentioned in this chapter), document converters [GOF95, page 110], and User Interface (UI) form creators [j.mp/pipbuild].

Some resources mention that the Builder pattern can also be used as a solution to the telescopic constructor problem [j.mp/wikibuilder]. 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, which are hard to manage. An example of

the telescopic constructor is listed at the stackoverflow website [j.mp/sobuilder]. Fortunately, this problem does not exist in Python, because it can be solved in at least two ways:

• With named parameters [j.mp/sobuipython]

• With argument list unpacking [j.mp/arglistpy]

At this point, the distinction between the Builder pattern and the Factory pattern might not be very clear. The main difference is that a Factory pattern creates an object in a single step, whereas a Builder pattern creates an object in multiple steps, and almost always through the use of a director. Some targeted implementations of the Builder pattern like Java's StringBuilder bypass the use of a director, but that's the exception to the rule.

Another difference is that while a Factory pattern returns a created object immediately, in the Builder pattern the client code explicitly asks the director

to return the final object when it needs it [GOF95, page 113], [j.mp/builderpat].The new computer analogy might help to distinguish between a Builder pattern and a Factory pattern. Assume that you want to buy a new computer. If you decide to

buy a specific preconfigured computer model, for example, the latest Apple 1.4 GHz Mac mini, you use the Factory pattern. All the hardware specifications are already predefined by the manufacturer, who knows what to do without consulting you. The

manufacturer typically receives just a single instruction. Code-wise, this would look like the following (apple-factory.py):

MINI14 = '1.4GHz Mac mini'class AppleFactory:

class MacMini14:

def __init__(self):

(45)

The Builder Pattern

[ 32 ]

self.hdd = 500 # in gigabytes self.gpu = 'Intel HD Graphics 5000' def __str__(self):

info = ('Model: {}'.format(MINI14),

'Memory: {}GB'.format(self.memory), 'Hard Disk: {}GB'.format(self.hdd), 'Graphics Card: {}'.format(self.gpu)) return '\n'.join(info)

def build_computer(self, model): if (model == MINI14):

return self.MacMini14() else:

print("I don't know how to build {}".format(model))if __name__ == '__main__':

afac = AppleFactory()

mac_mini = afac.build_computer(MINI14) print(mac_mini)

Notice the nested MacMini14 class. This is a neat way of forbidding the direct instantiation of a class.

Another option is buying a custom PC. In this case, you use the Builder pattern. You are the director that gives orders to the manufacturer (builder) about

your ideal computer specifications. Code-wise, this looks like the following (computer-builder.py):

class Computer:

def __init__(self, serial_number): self.serial = serial_number

self.memory = None # in gigabytes self.hdd = None # in gigabytes self.gpu = None

def __str__(self):

(46)

Chapter 2

[ 33 ]

class ComputerBuilder: def __init__(self):

self.computer = Computer('AG23385193') def configure_memory(self, amount):

self.computer.memory = amount def configure_hdd(self, amount): self.computer.hdd = amount def configure_gpu(self, gpu_model): self.computer.gpu = gpu_modelclass HardwareEngineer:

def __init__(self): self.builder = None

def construct_computer(self, memory, hdd, gpu): self.builder = ComputerBuilder()

[step for step in (self.builder.configure_memory(memory), self.builder.configure_hdd(hdd), self.builder.configure_gpu(gpu))] @property

def computer(self):

return self.builder.computerdef main():

engineer = HardwareEngineer()

engineer.construct_computer(hdd=500, memory=8, gpu='GeForce GTX 650 Ti')

computer = engineer.computer print(computer)

if __name__ == '__main__': main()

The basic changes are the introduction of a builder ComputerBuilder, a director HardwareEngineer, and the step-by-step construction of a computer, which now

supports different configurations (notice that memory, hdd, and gpu are parameters

and not preconfigured). What do we need to do if we want to support the construction of tablets? Implement this as an exercise.

(47)

The Builder Pattern

[ 34 ]

Implementation

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

(Video) Advanced Topics in Programming Languages Series: Python Design Patterns (part 2)

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 with importing the required modules and declaring a few Enum parameters [j.mp/pytenum] plus a constant that are 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

PizzaProgress = Enum('PizzaProgress', 'queued preparation baking ready')

PizzaDough = Enum('PizzaDough', 'thin thick')

PizzaSauce = Enum('PizzaSauce', 'tomato creme_fraiche')

PizzaTopping = Enum('PizzaTopping', 'mozzarella double_mozzarella bacon ham mushrooms red_onion oregano')

STEP_DELAY = 3 # in seconds for the sake of the example

Our end product is a pizza, which is described by the Pizza class. When using the Builder pattern, the end product does not have many responsibilities, since it is not supposed to be instantiated directly. A builder creates an instance of the end product and makes sure that it is properly prepared. That's why the Pizza class is so minimal. It basically initializes all data to sane default values. An exception is the prepare_dough() method. The prepare_dough() method is defined in the Pizzaclass instead of a builder for two reasons:

• To clarify the fact that the end product is typically minimal does not mean that you should never assign it any responsibilities

• To promote code reuse through composition [GOF95, page 32]

(48)

Chapter 2

[ 35 ]

def __str__(self): return self.name

def prepare_dough(self, dough): self.dough = dough

print('preparing the {} dough of your {}...'.format(self.dough.name, self)) time.sleep(STEP_DELAY)

print('done with the {} dough'.format(self.dough.name))

There are two builders: one for creating a margarita pizza (MargaritaBuilder) and another for creating a creamy bacon pizza (CreamyBaconBuilder). Each builder creates a Pizza instance and contains methods that follow the pizza-making procedure: prepare_dough(), add_sauce(), add_topping(), and bake(). To be precise, prepare_dough() is just a wrapper to the prepare_dough() method of the Pizza class. Notice how each builder takes care of all the pizza-specific details. For example, the topping of the margarita pizza is double mozzarella and oregano, while the topping of the creamy bacon pizza is mozzarella, bacon, ham, mushrooms, red onion, and oregano as follows:

class MargaritaBuilder:

def prepare_dough(self):

self.progress = PizzaProgress.preparation self.pizza.prepare_dough(PizzaDough.thin) def add_sauce(self):

print('adding the tomato sauce to your margarita...') self.pizza.sauce = PizzaSauce.tomato

time.sleep(STEP_DELAY)

print('done with the tomato sauce') def add_topping(self):

print('adding the topping (double mozzarella, oregano) to your margarita')

self.pizza.topping.append([i for i in

(PizzaTopping.double_mozzarella, PizzaTopping.oregano)]) time.sleep(STEP_DELAY)

(49)

The Builder Pattern

[ 36 ]

def bake(self):

self.progress = PizzaProgress.baking print('baking your margarita for {} seconds'.format(self.baking_time)) time.sleep(self.baking_time)

def prepare_dough(self):

self.progress = PizzaProgress.preparation self.pizza.prepare_dough(PizzaDough.thick) def add_sauce(self):

print('adding the crème fraîche sauce to your creamy bacon')

self.pizza.sauce = PizzaSauce.creme_fraiche time.sleep(STEP_DELAY)

print('done with the crème fraîche sauce') def add_topping(self):

print('adding the topping (mozzarella, bacon, ham, mushrooms, red onion, oregano) to your creamy bacon') self.pizza.topping.append([t for t in

(PizzaTopping.mozzarella, PizzaTopping.bacon, PizzaTopping.ham,PizzaTopping.mushrooms, PizzaTopping.red_onion, PizzaTopping.oregano)]) time.sleep(STEP_DELAY) seconds'.format(self.baking_time)) time.sleep(self.baking_time)

(50)

Chapter 2

[ 37 ]

The director in this example is the waiter. The core of the Waiter class is the construct_pizza() method, which accepts a builder as a parameter and executes all the pizza preparation steps in the right order. Choosing the appropriate builder, which can even be done in runtime, gives us the ability to create different pizza styles without modifying any code of the director (Waiter). The Waiter class also contains the pizza() method, which returns the end product (prepared pizza) as a variable to the caller as follows:

class Waiter:

def __init__(self): self.builder = None

def construct_pizza(self, builder): self.builder = builder

[step() for step in (builder.prepare_dough,

builder.add_sauce, builder.add_topping, builder.bake)] @property

def pizza(self):

return self.builder.pizza

The validate_style() function is similar to the validate_age() function as described in Chapter 1, The Factory Pattern. It is used to make sure that the user gives valid input, which in this case is a character that is mapped to a pizza builder. The m character uses the MargaritaBuilder class and the c character uses the CreamyBaconBuilder class. These mappings are in the builder parameter. A tuple

is returned, with the first element set to True if the input is valid, or False if it is invalid as follows:

def validate_style(builders): try:

pizza_style = input('What pizza would you like, [m]argarita or [c]reamy bacon? ')

builder = builders[pizza_style]() valid_input = True

except KeyError as err:

print('Sorry, only margarita (key m) and creamy bacon (key c) are available')

return (False, None) return (True, builder)

(51)

The Builder Pattern

[ 38 ]

The last part is the main() function. The main() function contains a code for instantiating a pizza builder. The pizza builder is then used by the Waiter director for preparing the pizza. The created pizza can be delivered to the client at any later point:

def main():

builders = dict(m=MargaritaBuilder, c=CreamyBaconBuilder) valid_input = False

while not valid_input:

valid_input, builder = validate_style(builders) print()

waiter = Waiter()

waiter.construct_pizza(builder) pizza = waiter.pizza

print()

print('Enjoy your {}!'.format(pizza))

To put all these things together, here's the complete code of this example (builder.py):

from enum import Enumimport time

PizzaProgress = Enum('PizzaProgress', 'queued preparation baking ready')

PizzaDough = Enum('PizzaDough', 'thin thick')

PizzaSauce = Enum('PizzaSauce', 'tomato creme_fraiche')

PizzaTopping = Enum('PizzaTopping', 'mozzarella double_mozzarella bacon ham mushrooms red_onion oregano')

def prepare_dough(self, dough): self.dough = dough

(52)

Chapter 2

[ 39 ]

time.sleep(STEP_DELAY)

print('done with the {} dough'.format(self.dough.name))class MargaritaBuilder:

def prepare_dough(self):

self.progress = PizzaProgress.preparation self.pizza.prepare_dough(PizzaDough.thin) def add_sauce(self):

print('adding the tomato sauce to your margarita...') self.pizza.sauce = PizzaSauce.tomato

time.sleep(STEP_DELAY)

print('done with the tomato sauce') def add_topping(self):

print('adding the topping (double mozzarella, oregano) to your margarita')

self.pizza.topping.append([i for i in

(53)

The Builder Pattern

[ 40 ]

def prepare_dough(self):

self.progress = PizzaProgress.preparation self.pizza.prepare_dough(PizzaDough.thick) def add_sauce(self):

print('adding the crème fraîche sauce to your creamy bacon')

self.pizza.sauce = PizzaSauce.creme_fraiche time.sleep(STEP_DELAY)

print('done with the crème fraîche sauce') def add_topping(self):

print('adding the topping (mozzarella, bacon, ham, mushrooms, red onion, oregano) to your creamy bacon') self.pizza.topping.append([t for t in

(PizzaTopping.mozzarella, PizzaTopping.bacon, PizzaTopping.ham,PizzaTopping.mushrooms, PizzaTopping.red_onion, PizzaTopping.oregano)]) time.sleep(STEP_DELAY)

print('done with the topping (mozzarella, bacon, ham, mushrooms, red onion, oregano)')

def bake(self):

self.progress = PizzaProgress.baking print('baking your creamy bacon for {} seconds'.format(self.baking_time)) time.sleep(self.baking_time)

self.progress = PizzaProgress.ready print('your creamy bacon is ready')class Waiter:

def __init__(self): self.builder = None

def construct_pizza(self, builder): self.builder = builder

[step() for step in (builder.prepare_dough,

builder.add_sauce, builder.add_topping, builder.bake)] @property

def pizza(self):

(54)

Chapter 2

builders = dict(m=MargaritaBuilder, c=CreamyBaconBuilder) valid_input = False

while not valid_input:

valid_input, builder = validate_style(builders) print()

waiter = Waiter()

waiter.construct_pizza(builder) pizza = waiter.pizza

print()

print('Enjoy your {}!'.format(pizza))if __name__ == '__main__':

main()

A sample output of this example is as follows:

>>> python3 builder.py

What pizza would you like, [m]argarita or [c]reamy bacon? r

Sorry, only margarita (key m) and creamy bacon (key c) are availableWhat pizza would you like, [m]argarita or [c]reamy bacon? m

preparing the thin dough of your margarita...done with the thin dough

adding the tomato sauce to your margarita...done with the tomato sauce

adding the topping (double mozzarella, oregano) to your margaritadone with the topping (double mozzarella, oregano)

baking your margarita for 5 secondsyour margarita is ready

(55)

The Builder Pattern

[ 42 ]

Supporting only two pizza types is a shame. Implement a Hawaiian pizza builder. Consider using inheritance after thinking about the advantages and disadvantages. Check the ingredients of a typical Hawaiian pizza and decide which class you need to extend: MargaritaBuilder or CreamyBaconBuilder? Perhaps both [j.mp/pymulti]?

In the book, Effective Java (2nd edition), Joshua Bloch describes an interesting variation of the Builder pattern where calls to builder methods are chained. This is

accomplished by defining the builder itself as an inner class and returning itself from

each of the setter-like methods on it. The build() method returns the final object. This pattern is called the Fluent Builder. Here's a Python implementation, which was kindly provided by a reviewer of the book:

class Pizza:

def __init__(self, builder): self.garlic = builder.garlic

Adapt the pizza example to make use of the Fluent Builder pattern. Which version

(56)

Chapter 2

[ 43 ]

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. A Builder pattern is usually a better candidate than a Factory pattern when:

• We want to create a complex object (an object composed of many parts

and created in different steps that might need to follow a specific order). • Different representations of an object are required, and we want to keep

the construction of an object decoupled from its representation

• We want to create an object at one point in time but access it at a later pointWe 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 a Builder pattern and a Factory pattern, and

gave a preconfigured (Factory) versus customer (Builder) computer order analogy

to clarify them.

In the implementation part, we have seen how to create a pizza ordering application, which has preparation dependencies. There are many recommended interesting exercises in this chapter, including implementing a Fluent Builder.

(Video) Bridge Pattern – Design Patterns (ep 11)

(57)

Videos

1. Looking at COBOL from a Python Perspective
(Code & Supply)
2. Design Patterns: Don't Repeat Yourself in C#
(IAmTimCorey)
3. How to start learning low level design using these five books and the order in which to read.
(sudoCODE)
4. Microservices Full Course - Learn Microservices in 4 Hours | Microservices Tutorial | Edureka
(edureka!)
5. Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges
(freeCodeCamp.org)
6. Raymond Hettinger «Build powerful, new data structures with Python's abstract base classes»
(Видео с мероприятий IT-People)

Top Articles

You might also like

Latest Posts

Article information

Author: The Hon. Margery Christiansen

Last Updated: 01/07/2023

Views: 6296

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.