Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering Python Design Patterns
Mastering Python Design Patterns

Mastering Python Design Patterns: A guide to creating smart, efficient, and reusable software , Second Edition

Arrow left icon
Profile Icon Kamon Ayeva Profile Icon Kasampalis
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (9 Ratings)
Paperback Aug 2018 248 pages 2nd Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Kamon Ayeva Profile Icon Kasampalis
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (9 Ratings)
Paperback Aug 2018 248 pages 2nd Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Mastering Python Design Patterns

The Factory Pattern

Design patterns are reusable programming solutions that have been used in various real-world contexts, and have proved to produce expected results. They are shared among programmers and continue being improved over time. This topic is popular thanks to the book by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, titled Design Patterns: Elements of Reusable Object-Oriented Software.

Gang of Four: The book by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides is also called the Gang of Four book for short (or GOF book for even shorter).

Here is a quote about design patterns from the Gang of Four book:

A design pattern systematically names, motivates, and explains a general design that addresses a recurring design problem in object-oriented systems. It describes the problem, the solution, when to apply the solution, and its consequences. It also gives implementation hints and examples. The solution is a general arrangement of objects and classes that solve the problem. The solution is customized and implemented to solve the problem in a particular context.

There are several categories of design patterns used in object-oriented programming, depending on the type of problem they address and/or the types of solutions they help us build. In their book, the Gang of Four present 23 design patterns, split into three categories: creational, structural, and behavioral.

Creational design patterns are the first category we will cover throughout this chapter, and Chapters 2, The Builder Pattern and Chapter 3, Other Creational Patterns. These patterns deal with different aspects of object creation. Their goal is to provide better alternatives for situations where direct object creation, which in Python happens within the __init__() function, is not convenient.

See https://docs.python.org/3/tutorial/classes.html for a quick overview of object classes and the special __init__() method Python uses to initialize a new class instance.

We will start with the first creational design pattern from the Gang of Four book: the factory design pattern. In the factory design pattern, a client (meaning client code) 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 the object creation process. It is easier to track which objects are created if this is done through a central function, compared to letting a client create objects using a direct class instantiation. A factory reduces the complexity of maintaining an application by decoupling the code that creates an object from the code that uses it.

Factories typically come in two forms—the factory method, which is a method (or simply a function for a Python developer) that returns a different object per input parameter, and the abstract factory, which is a group of factory methods used to create a family of related objects.

In this chapter, we will discuss:

  • The factory method
  • The abstract factory

The factory method

The factory method is based on a single function written to handle our object creation task. We execute it, passing a parameter that provides information about what we want, and, as a result, the wanted object is created.

Interestingly, when using the factory method, we are not required to know any details about how the resulting object is implemented and where it is coming from.

Real-world examples

An example of the factory method pattern used in reality is in the context of a plastic toy construction kit. The molding material used to construct plastic toys is the same, but different toys (different figures or shapes) can be produced using the right plastic molds. This is like having a factory method in which the input is the name of the toy that we want (for example, duck or car) and the output (after the molding) is the plastic toy that was requested.

In the software world, the Django web framework uses the factory method pattern for creating the fields of a web form. The forms module, included in Django, supports the creation of different kinds of fields (for example, CharField, EmailField, and so on). And parts of their behavior can be customized using attributes such as max_length or required (j.mp/djangofac). As an illustration, there follows a snippet that a developer could write for a form (the PersonForm form containing the fields name and birth_date) as part of a Django application's UI code:

from django import forms

class PersonForm(forms.Form):
    name = forms.CharField(max_length=100)
    birth_date = forms.DateField(required=False)

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 in a single function/method, you should consider using the factory method pattern. The factory method centralizes object creation and tracking your objects becomes much easier. Note that it is absolutely fine to create more than one factory method, and this is how it is typically done in practice. Each factory method logically groups the creation of objects that have similarities. For example, one factory method might be responsible for connecting you to different databases (MySQL, SQLite), another factory method might be responsible for creating the geometrical object that you request (circle, triangle), and so on.

The factory method is also useful when you want to decouple object creation from 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 and does not require any changes to the code that uses it.

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. 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:
pass

if __name__ == '__main__':
a = A()
b = A()
print(id(a) == id(b))
print(a, b)

Executing the python id.py command on my computer results in the following output:

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 the ones 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 (REPL)—or simply put, the interactive prompt—but that's a REPL-specific optimization which does not happen normally.

Implementing the factory method

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, RSS/Atom, YAML, and JSON. Examples of binary files are the .sq3 file format used by SQLite and the .mp3 audio 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 that you work with human-readable files, unless there are other restrictions that do not allow it (mainly unacceptable performance and proprietary binary formats).

In this case, 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 JSON file, movies.json, is an example (found on GitHub) of a dataset containing information about American movies (title, year, director name, genre, and so on). This is actually a big file but here is an extract, simplified for better readability, to show how its content is organized:

[
{"title":"After Dark in Central Park",
"year":1900,
"director":null, "cast":null, "genre":null},
{"title":"Boarding School Girls' Pajama Parade",
"year":1900,
"director":null, "cast":null, "genre":null},
{"title":"Buffalo Bill's Wild West Parad",
"year":1900,
"director":null, "cast":null, "genre":null},
{"title":"Caught",
"year":1900,
"director":null, "cast":null, "genre":null},
{"title":"Clowns Spinning Hats",
"year":1900,
"director":null, "cast":null, "genre":null},
{"title":"Capture of Boer Battery by British",
"year":1900,
"director":"James H. White", "cast":null, "genre":"Short documentary"},
{"title":"The Enchanted Drawing",
"year":1900,
"director":"J. Stuart Blackton", "cast":null,"genre":null},
{"title":"Family Troubles",
"year":1900,
"director":null, "cast":null, "genre":null},
{"title":"Feeding Sea Lions",
"year":1900,
"director":null, "cast":"Paul Boyton", "genre":null}
]

The XML file, person.xml, is based on a Wikipedia example (j.mp/wikijson), and contains information about individuals (firstName, lastName, gender, and so on) as follows:

  1. We start with the enclosing tag of the persons XML container:
<persons> 
  1. Then, an XML element representing a person's data code is presented as follows:
<person> 
<firstName>John</firstName>
<lastName>Smith</lastName>
<age>25</age>
<address>
<streetAddress>21 2nd Street</streetAddress>
<city>New York</city>
<state>NY</state>
<postalCode>10021</postalCode>
</address>
<phoneNumbers>
<phoneNumber type="home">212 555-1234</phoneNumber>
<phoneNumber type="fax">646 555-4567</phoneNumber>
</phoneNumbers>
<gender>
<type>male</type>
</gender>
</person>
  1. An XML element representing another person's data is shown by the following code:
<person> 
<firstName>Jimy</firstName>
<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>
<gender>
<type>male</type>
</gender>
</person>
  1. An XML element representing a third person's data is shown by the code:
<person> 
<firstName>Patty</firstName>
<lastName>Liar</lastName>
<age>20</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>
<phoneNumber type="mobile">001 452-8819</phoneNumber>
</phoneNumbers>
<gender>
<type>female</type>
</gender>
</person>
  1. Finally, we close the XML container:
</persons>

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

import json
import xml.etree.ElementTree as etree

The JSONDataExtractor 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 attribute instead of a method, as follows:

class JSONDataExtractor:
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 XMLDataExtractor 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 XMLDataExtractor:
def __init__(self, filepath):
self.tree = etree.parse(filepath)
@property
def parsed_data(self):
return self.tree

The dataextraction_factory() function is a factory method. It returns an instance of JSONDataExtractor or XMLDataExtractor depending on the extension of the input file path as follows:

def dataextraction_factory(filepath):
if filepath.endswith('json'):
extractor = JSONDataExtractor
elif filepath.endswith('xml'):
extractor = XMLDataExtractor
else:
raise ValueError('Cannot extract data from {}'.format(filepath))
return extractor(filepath)

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

def extract_data_from(filepath):
factory_obj = None
try:
factory_obj = dataextraction_factory(filepath)
except ValueError as e:
print(e)
return factory_obj

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 = extract_data_from('data/person.sq3')
print()

The next part shows how to work with the JSON files using the factory method. Based on the parsing, the title, year, director name, and genre of the movie can be shown (when the value is not empty), as follows:

json_factory = extract_data_from('data/movies.json')
json_data = json_factory.parsed_data
print(f'Found: {len(json_data)} movies')
for movie in json_data:
print(f"Title: {movie['title']}")
year = movie['year']
if year:
print(f"Year: {year}")
director = movie['director']
if director:
print(f"Director: {director}")
genre = movie['genre']
if genre:
print(f"Genre: {genre}")
print()

The final part shows you 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 (using liars = xml_data.findall(f".//person[lastName='Liar']")). For each matched person, the basic name and phone number information are shown, as follows:

xml_factory = extract_data_from('data/person.xml')
xml_data = xml_factory.parsed_data
liars = xml_data.findall(f".//person[lastName='Liar']")
print(f'found: {len(liars)} persons')
for liar in liars:
firstname = liar.find('firstName').text
print(f'first name: {firstname}')
lastname = liar.find('lastName').text
print(f'last name: {lastname}')
[print(f"phone number ({p.attrib['type']}):", p.text)
for p in liar.find('phoneNumbers')]
print()

Here is the summary of the implementation (you can find the code in the factory_method.py file):

  1. We start by importing the modules we need (json and ElementTree).
  2. We define the JSON data extractor class (JSONDataExtractor).
  3. We define the XML data extractor class (XMLDataExtractor).
  4. We add the factory function, dataextraction_factory(), for getting the right data extractor class.
  5. We also add our wrapper for handling exceptions, the extract_data_from() function.
  6. Finally, we have the main() function, followed by Python's conventional trick for calling it when invoking this file from the command line. The following are the aspects of the main function:
    • We try to extract data from an SQL file (data/person.sq3), to show how the exception is handled
    • We extract data from a JSON file and parse the result
    • We extract data from an XML file and parse the result

The following is the type of output (for the different cases) you will get by calling the python factory_method.py command.

First, there is an exception message when trying to access an SQLite (.sq3) file:

Then, we get the following result from processing the movies file (JSON):

Finally, we get this result from processing the person XML file to find the people whose last name is Liar:

Notice that although JSONDataExtractor and XMLDataExtractor 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 data extractor. Although it would be nice to be able to use the same code for all extractors, this is not realistic for the most part, 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 code for handling the XML and JSON files, what changes are required to support a third format, for example, SQLite? Find an SQLite file, or create your own and try it.

The abstract factory

The abstract factory design pattern is a generalization of the 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.

We are going to discuss some examples, use cases, and a possible implementation.

Real-world examples

The 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.

In the software category, the factory_boy (https://github.com/FactoryBoy/factory_boy) package provides 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, this way, your tests become readable and you avoid sharing unnecessary code.

Django models are special classes used by the framework to help store and interact with data in the database (tables). See the Django documentation (https://docs.djangoproject.com) for more details.

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 object creation from 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 to create 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 (at runtime) by changing the active factory method. The classic example is 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.

Implementing the abstract factory pattern

To demonstrate the abstract factory pattern, I will reuse one of my favorite examples, included in the book, Python 3 Patterns, Recipes and Idioms, by Bruce Eckel. Imagine that we are creating a game or we want to include a mini-game as part of our application to entertain our users. We want to include at least two games, one for children and one for adults. We will decide which game to create and launch at runtime, based on user input. An abstract factory takes care of the game creation part.

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 at runtime. The interact_with() method is used to describe the interaction of the frog with an obstacle (for example, a bug, puzzle, and other frogs) as follows:

class Frog:
def __init__(self, name):
self.name = name

def __str__(self):
return self.name

def interact_with(self, obstacle):
act = obstacle.action()
msg = f'{self} the Frog encounters {obstacle} and {act}!'
print(msg)

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:
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) in the game. Keeping the creation methods separate and their names generic (for example, make_character() and make_obstacle()) allows us to change the active factory (and therefore the active game) dynamically 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 at runtime (j.mp/ginstromdp). The code is as follows:

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()

The WizardWorld game is similar. The only difference is that the wizard battles against monsters such as orks instead of eating bugs!

Here is the definition of the Wizard class, which is similar to the Frog one:

class Wizard:
def __init__(self, name):
self.name = name

def __str__(self):
return self.name

def interact_with(self, obstacle):
act = obstacle.action()
msg = f'{self} the Wizard battles against {obstacle}
and {act}!'
print(msg)

Then, the definition of the Ork class is as follows:

class Ork: 
def __str__(self):
return 'an evil ork'

def action(self):
return 'kills it'

We also need to define the WizardWorld class, similar to the FrogWorld one that we have discussed; the obstacle, in this case, is an Ork instance:

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):
return Ork()

The GameEnvironment class is the main entry point of our game. It accepts the 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):
try:
age = input(f'Welcome {name}. How old are you? ')
age = int(age)
except ValueError as err:
print(f"Age {age} is invalid, please try again...")
return (False, age)
return (True, age)

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

def main():
name = input("Hello. What's your name? ")
valid_input = False
while not valid_input:
valid_input, age = validate_age(name)
game = FrogWorld if age < 18 else WizardWorld
environment = GameEnvironment(game(name))
environment.play()

The summary for the implementation we just discussed (see the complete code in the abstract_factory.py file) is as follows:

  1. We define the Frog and Bug classes for the FrogWorld game.
  2. We add the FrogWorld class, where we use our Frog and Bug classes.
  1. We define the Wizard and Ork classes for the WizardWorld game.
  2. We add the WizardWorld class, where we use our Wizard and Ork classes.
  3. We define the GameEnvironment class.
  4. We add the validate_age() function.
  5. Finally, we have the main() function, followed by the conventional trick for calling it. The following are the aspects of this function:
    • We get the user's input for name and age
    • We decide which game class to use based on the user's age
    • We instantiate the right game class, and then the GameEnvironment class
    • We call .play() on the environment object to play the game

Let's call this program using the python abstract_factory.py command, and see some sample output.

The sample output for a teenager is as follows:

The sample output for an adult is as follows:

Try extending the game to make it more complete. You can go as far as you want; create 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 track object creation, decouple object creation from object usage, or even improve the performance and resource usage of an application. Improving the performance was not demonstrated in this chapter. You might consider trying 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 provided 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 to car manufacturing, how the django_factory package for Django makes use of it to create clean tests, and then we covered its common use cases. Our implementation example 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 discuss the builder pattern, which is another creational pattern that can be used for fine-tuning the creation of complex objects.

Left arrow icon Right arrow icon

Key benefits

  • Master the application design using the core design patterns and latest features of Python 3.7
  • Learn tricks to solve common design and architectural challenges
  • Choose the right plan to improve your programs and increase their productivity

Description

Python is an object-oriented scripting language that is used in a wide range of categories. In software engineering, a design pattern is an elected solution for solving software design problems. Although they have been around for a while, design patterns remain one of the top topics in software engineering, and are a ready source for software developers to solve the problems they face on a regular basis. This book takes you through a variety of design patterns and explains them with real-world examples. You will get to grips with low-level details and concepts that show you how to write Python code, without focusing on common solutions as enabled in Java and C++. You'll also fnd sections on corrections, best practices, system architecture, and its designing aspects. This book will help you learn the core concepts of design patterns and the way they can be used to resolve software design problems. You'll focus on most of the Gang of Four (GoF) design patterns, which are used to solve everyday problems, and take your skills to the next level with reactive and functional patterns that help you build resilient, scalable, and robust applications. By the end of the book, you'll be able to effciently address commonly faced problems and develop applications, and also be comfortable working on scalable and maintainable projects of any size.

Who is this book for?

This book is for intermediate Python developers. Prior knowledge of design patterns is not required to enjoy this book.

What you will learn

  • Explore Factory Method and Abstract Factory for object creation
  • Clone objects using the Prototype pattern
  • Make incompatible interfaces compatible using the Adapter pattern
  • Secure an interface using the Proxy pattern
  • Choose an algorithm dynamically using the Strategy pattern
  • Keep the logic decoupled from the UI using the MVC pattern
  • Leverage the Observer pattern to understand reactive programming
  • Explore patterns for cloud-native, microservices, and serverless architectures

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 31, 2018
Length: 248 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788837484
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 31, 2018
Length: 248 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788837484
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
Mastering Python Design Patterns
€36.99
Modern Python Standard Library Cookbook
€41.99
Clean Code in Python
€36.99
Total 115.97 Stars icon
Banner background image

Table of Contents

16 Chapters
The Factory Pattern Chevron down icon Chevron up icon
The Builder Pattern Chevron down icon Chevron up icon
Other Creational Patterns Chevron down icon Chevron up icon
The Adapter Pattern Chevron down icon Chevron up icon
The Decorator Pattern Chevron down icon Chevron up icon
The Bridge Pattern Chevron down icon Chevron up icon
The Facade Pattern Chevron down icon Chevron up icon
Other Structural Patterns Chevron down icon Chevron up icon
The Chain of Responsibility Pattern Chevron down icon Chevron up icon
The Command Pattern Chevron down icon Chevron up icon
The Observer Pattern Chevron down icon Chevron up icon
The State Pattern Chevron down icon Chevron up icon
Other Behavioral Patterns Chevron down icon Chevron up icon
The Observer Pattern in Reactive Programming Chevron down icon Chevron up icon
Microservices and Patterns for the Cloud Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3
(9 Ratings)
5 star 44.4%
4 star 0%
3 star 0%
2 star 55.6%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Edward Nov 27, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There's a few typos scattered throughout, but the catalog is excellent overall. It's well written and worth the cost.
Amazon Verified review Amazon
Gianguglielmo Calvi Oct 10, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am part of the generation of coders and designers that developed their core knowledge around three fundamental books:"The C++ Programming Language", "Modern C++ Design: Generic Programming and Design Patterns Applied", and "Design Patterns: Elements of Reusable Object-Oriented Software".The latter is mentioned in the very first paragraph of Mastering Python Design Patters and I can't deny that this sounded already a very positive beginning to me.I would define MPDP has a "necessary" book; it organizes important architectural design principles around python philosophy and instruct on how to get the best out of this powerful language.Its reading is smooth, accompanied by clear and well chosen examples, and by references to existing services that showcase important aspects of the techniques explained.All the most important design patterns are explored and even for those with a deep understanding of the subject will be pleasurable to discover how python is able to elegantly express them.The last sections with an overview of the Microservices and Design for the Cloud approaches, are a good bonus to see how everlasting techniques applies to contemporary scenarios.Last but not least, I have appreciated the <Other Books you may enjoy> section: it is always good to have trusted pointers to resources for extending our knowledge on a topic.MPDP is a book that I would suggest to anyone willing to raise the quality, scalability and robustness of its work with python: being a coder or a designer, you will benefit either way from the understanding of how patters interact and how complex architectures should be organized to work efficiently.
Amazon Verified review Amazon
:D Aug 24, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Especially helpful are1. Real-world examples and Use cases for the pattern.2. Discussion the Pythonic way of applying design patterns.
Amazon Verified review Amazon
Aleemuddin Aug 22, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good
Amazon Verified review Amazon
Amazon Customer Mar 13, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
When reading chapters like the abstract factory patterns, it seems that the authors haven't unterstood it themselves. Otherwise they could have explained why it is called abstract. The explanation e.g. is, that a normal factory is just a function and an abstract factory is the same in methods of classes. This is just wrong.All in all it doesn't make any sense to force every in Java developed Design Pattern on Python without discussion the specialty why it is even needen in Python and how the shown implementation differs from the original concept.Besides that there are too many sloppy, non pythonic idioms in the code, and many examples for how not to do it, for example using string formatting for SQL-Parameter.For a second edition of a book that is not acceptable.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.