Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
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.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> Design Patterns> Mastering Python Design Patterns
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 AyevaProfile Icon Sakis Kasampalis
Arrow right icon
₹700₹2919.99
Full star iconFull star iconFull star iconHalf star iconEmpty star icon3.3(9 Ratings)
eBookAug 2018248 pages2nd Edition
eBook
₹700 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m
Arrow left icon
Profile Icon Kamon AyevaProfile Icon Sakis Kasampalis
Arrow right icon
₹700₹2919.99
Full star iconFull star iconFull star iconHalf star iconEmpty star icon3.3(9 Ratings)
eBookAug 2018248 pages2nd Edition
eBook
₹700 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹700 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview 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, titledDesign 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 theGang of Four book for short (orGOF book for even shorter).

Here is a quote about design patterns from theGang 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 inobject-oriented programming, depending on the type of problem they address and/or the types of solutions they help us build. In their book, theGang of Four present 23 design patterns, split into three categories:creational,structural, andbehavioral.

Creational design patterns are the first category we will cover throughout this chapter, andChapters 2,The Builder Pattern andChapter 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.

Seehttps://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 theGang of Four book: the factory design pattern. In the factory design pattern, aclient (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—thefactory method, which is a method (or simply a function for a Python developer) that returns a different object per input parameter, and theabstract 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 orcar) 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. Theforms 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 asmax_length orrequired (j.mp/djangofac). As an illustration, there follows a snippet that a developer could write for a form (thePersonForm form containing the fieldsname andbirth_date) as part of a Django application's UI code:

fromdjangoimportformsclass 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 (fileid.py), it creates two instances of the same class,A, and uses theid() function to compare theirmemory 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 thepython 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 PythonRead-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 andxml.etree.ElementTree, as follows:

import json
import xml.etree.ElementTree as etree

TheJSONDataExtractor class parses the JSON file and has aparsed_data() method that returns all data as a dictionary (dict). The property decorator is used to makeparsed_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

TheXMLDataExtractor class parses the XML file and has aparsed_data() method that returns all data as a list ofxml.etree.Element as follows:

class XMLDataExtractor:
def __init__(self, filepath):
self.tree = etree.parse(filepath)
@property
def parsed_data(self):
return self.tree

Thedataextraction_factory() function is a factory method. It returns an instance ofJSONDataExtractor orXMLDataExtractor 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)

Theextract_data_from() function is a wrapper ofdataextraction_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

Themain() 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 nameLiar (usingliars = 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 thefactory_method.py file):

  1. We start by importing the modules we need (json andElementTree).
  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, theextract_data_from() function.
  6. Finally, we have themain() function, followed by Python's conventional trick for calling it when invoking this file from the command line. The following are the aspects of themain 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 thepython 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 themovies file (JSON):

Finally, we get this result from processing theperson XML file to find the people whose last name isLiar:

Notice that althoughJSONDataExtractor andXMLDataExtractor have the same interfaces, what is returned byparsed_data() is not handled in a uniform way. Different Python code must be used to work with eachdata 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, thefactory_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 supporttest-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 calledFrogWorld. 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. Theinteract_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'

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

TheWizardWorld game is similar. The only difference is that the wizard battles against monsters such asorks instead of eating bugs!

Here is the definition of theWizard class, which is similar to theFrog 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 theOrk class is as follows:

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

def action(self):
return 'kills it'

We also need to define theWizardWorld class, similar to theFrogWorld one that we have discussed; the obstacle, in this case, is anOrk 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()

TheGameEnvironment 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. Theplay() 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)

Thevalidate_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 toFalse. If the age is fine, the first element of the tuple is set toTrue 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 themain() 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 theabstract_factory.py file) is as follows:

  1. We define theFrog andBug classes for the FrogWorld game.
  2. We add theFrogWorld class, where we use ourFrog andBug classes.
  1. We define theWizard andOrk classes for the WizardWorld game.
  2. We add theWizardWorld class, where we use ourWizard andOrk classes.
  3. We define theGameEnvironment class.
  4. We add thevalidate_age() function.
  5. Finally, we have themain() 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 theGameEnvironment class
    • We call.play() on the environment object to play the game

Let's call this program using thepython 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 thedjango_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.

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
Languages :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
₹4500billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick iconExclusive print discounts
₹5000billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick iconExclusive print discounts

Frequently bought together


Clean Code in Python
Clean Code in Python
Read more
Aug 2018332 pages
Full star icon3.7 (3)
eBook
eBook
₹700₹2919.99
₹3649.99
Mastering Python Design Patterns
Mastering Python Design Patterns
Read more
Aug 2018248 pages
Full star icon3.3 (9)
eBook
eBook
₹700₹2919.99
₹3649.99
Modern Python Standard Library Cookbook
Modern Python Standard Library Cookbook
Read more
Aug 2018366 pages
Full star icon4.4 (7)
eBook
eBook
₹700₹3276.99
₹4096.99
Stars icon
Total11,396.97
Clean Code in Python
₹3649.99
Mastering Python Design Patterns
₹3649.99
Modern Python Standard Library Cookbook
₹4096.99
Total11,396.97Stars icon
Buy 2+ to unlock₹600 prices - master what's next.
SHOP NOW

Table of Contents

16 Chapters
The Factory PatternChevron down iconChevron up icon
The Factory Pattern
The factory method
The abstract factory
Summary
The Builder PatternChevron down iconChevron up icon
The Builder Pattern
Real-world examples
Use cases
Implementation
Summary
Other Creational PatternsChevron down iconChevron up icon
Other Creational Patterns
The prototype pattern
Singleton
Summary
The Adapter PatternChevron down iconChevron up icon
The Adapter Pattern
Real-world examples
Use cases
Implementation
Summary
The Decorator PatternChevron down iconChevron up icon
The Decorator Pattern
Real-world examples
Use cases
Implementation
Summary
The Bridge PatternChevron down iconChevron up icon
The Bridge Pattern
Real-world examples
Use cases
Implementation
Summary
The Facade PatternChevron down iconChevron up icon
The Facade Pattern
Real-world examples
Use cases
Implementation
Summary
Other Structural PatternsChevron down iconChevron up icon
Other Structural Patterns
The flyweight pattern
The model-view-controller pattern
The proxy pattern
Summary
The Chain of Responsibility PatternChevron down iconChevron up icon
The Chain of Responsibility Pattern
Real-world examples
Use cases
Implementation
Summary
The Command PatternChevron down iconChevron up icon
The Command Pattern
Real-world examples
Use cases
Implementation
Summary
The Observer PatternChevron down iconChevron up icon
The Observer Pattern
Real-world examples
Use cases
Implementation
Summary
The State PatternChevron down iconChevron up icon
The State Pattern
Real-world examples
Use cases
Implementation
Summary
Other Behavioral PatternsChevron down iconChevron up icon
Other Behavioral Patterns
Interpreter pattern
Strategy pattern
Memento pattern
Iterator pattern
Template pattern
Summary
The Observer Pattern in Reactive ProgrammingChevron down iconChevron up icon
The Observer Pattern in Reactive Programming
Real-world examples
Use cases
Implementation
Summary
Microservices and Patterns for the CloudChevron down iconChevron up icon
Microservices and Patterns for the Cloud
The Microservices pattern
The Retry pattern
The Circuit Breaker pattern
The Cache-Aside pattern
Throttling
Summary
Other Books You May EnjoyChevron down iconChevron up icon
Other Books You May Enjoy
Leave a review - let other readers know what you think

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
Full star icon5 (1)
eBook
eBook
₹700₹2382.99
₹2978.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
₹700₹2382.99
₹2978.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (64)
eBook
eBook
₹700₹2978.99
₹3723.99
₹3723.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
₹700₹2502.99
₹3127.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024504 pages
Full star icon4.7 (13)
eBook
eBook
₹700₹2978.99
₹3723.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon3.5 (2)
eBook
eBook
₹700₹2382.99
₹2978.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Sep 202557hrs 40mins
Full star icon5 (1)
Video
Video
₹700₹5585.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (17)
eBook
eBook
₹700₹3276.99
₹4096.99
Right arrow icon

Customer reviews

Top Reviews
Rating distribution
Full star iconFull star iconFull star iconHalf star iconEmpty star icon3.3
(9 Ratings)
5 star44.4%
4 star0%
3 star0%
2 star55.6%
1 star0%
Filter icon Filter
Top Reviews

Filter reviews by




EdwardNov 27, 2019
Full star iconFull star iconFull star iconFull star iconFull star icon5
There's a few typos scattered throughout, but the catalog is excellent overall. It's well written and worth the cost.
Amazon Verified reviewAmazon
Gianguglielmo CalviOct 10, 2018
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
:DAug 24, 2020
Full star iconFull star iconFull star iconFull star iconFull star icon5
Especially helpful are1. Real-world examples and Use cases for the pattern.2. Discussion the Pythonic way of applying design patterns.
Amazon Verified reviewAmazon
AleemuddinAug 22, 2019
Full star iconFull star iconFull star iconFull star iconFull star icon5
Good
Amazon Verified reviewAmazon
Amazon CustomerMar 13, 2020
Full star iconFull star iconEmpty star iconEmpty star iconEmpty star icon2
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 reviewAmazon
  • Arrow left icon Previous
  • 1
  • 2
  • Arrow right icon Next

People who bought this also bought

Left arrow icon
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (64)
eBook
eBook
₹700₹2978.99
₹3723.99
₹3723.99
Event-Driven Architecture in Golang
Event-Driven Architecture in Golang
Read more
Nov 2022384 pages
Full star icon4.9 (10)
eBook
eBook
₹700₹2978.99
₹3723.99
₹3351.99
The Python Workshop Second Edition
The Python Workshop Second Edition
Read more
Nov 2022600 pages
Full star icon4.6 (19)
eBook
eBook
₹700₹3562.99
₹3872.99
Template Metaprogramming with C++
Template Metaprogramming with C++
Read more
Aug 2022480 pages
Full star icon4.6 (13)
eBook
eBook
₹700₹3220.99
₹3500.99
Domain-Driven Design with Golang
Domain-Driven Design with Golang
Read more
Dec 2022204 pages
Full star icon4.4 (18)
eBook
eBook
₹700₹2680.99
₹3351.99
Right arrow icon

About the authors

Left arrow icon
Profile icon Kamon Ayeva
Kamon Ayeva
LinkedIn iconGithub icon
Kamon Ayeva is a seasoned Python expert with over two decades of experience in the technology sector. As the founder of Content Gardening Studio, a consulting and custom development services firm, he specializes in web development, data, and AI, delivering top-notch Python solutions to clients globally. A trusted educator, Kamon has trained numerous developers, solidifying his reputation as an authority in the Python community. He is also the co-author of the previous edition of Mastering Python Design Patterns. On social media, you can find him on Twitter, where he continues to share invaluable insights and trends in Python and software design.
Read more
See other products by Kamon Ayeva
Profile icon Sakis Kasampalis
Sakis Kasampalis
Sakis Kasampalis is a software architect 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.
Read more
See other products by Sakis Kasampalis
Right arrow icon
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Create a Free Account To Continue Reading

Modal Close icon
OR
    First name is required.
    Last name is required.

The Password should contain at least :

  • 8 characters
  • 1 uppercase
  • 1 number
Notify me about special offers, personalized product recommendations, and learning tips By signing up for the free trial you will receive emails related to this service, you can unsubscribe at any time
By clicking ‘Create Account’, you are agreeing to ourPrivacy Policy andTerms & Conditions
Already have an account? SIGN IN

Sign in to activate your 7-day free access

Modal Close icon
OR
By redeeming the free trial you will receive emails related to this service, you can unsubscribe at any time.

[8]ページ先頭

©2009-2025 Movatter.jp