34,79 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 266
Veröffentlichungsjahr: 2018
Copyright © 2018 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 authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor: Richa TripathiAcquisition Editor: Karan SadawanaContent Development Editor: Anugraha ArunagiriTechnical Editors: Jash Bhavishi, Supriya ThabeCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Tom ScariaProduction Coordinator: Nilesh Mohite
First published: January 2015 Second edition: August 2018
Production reference: 1300818
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-748-4
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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 [email protected] 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.
Kamon Ayeva is a web developer/DevOps engineer working with a variety of tools. He spends most of his time building projects using Python's powerful scripting capabilities, add-on libraries, and web frameworks such as Django or Flask. Kamon has been using Python in professional contexts for more than 12 years. He is also a Python instructor with a passion for teaching how to use Python features to quickly produce results.
Sakis Kasampalis 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 LearningPython Design Patterns, published by Packt Publishing.
Gaurav Aroraa has an M.Phil in computer science. He is a Microsoft MVP, a lifetime member of Computer Society of India (CSI), an advisory member of IndiaMentor, certified as a Scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. He is an open source developer, a contributor to TechNet Wiki, and the founder of Ovatic Systems Private Limited. In 20+ years of his career, he has mentored thousands of students and industry professionals. You can tweet Gaurav on his Twitter handle @g_arora.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Mastering Python Design Patterns Second Edition
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
The Factory Pattern
The factory method
Real-world examples
Use cases
Implementing the factory method
The abstract factory
Real-world examples
Use cases
Implementing the abstract factory pattern
Summary
The Builder Pattern
Real-world examples
Use cases
Implementation
Summary
Other Creational Patterns
The prototype pattern
Real-world examples
Use cases
Implementation
Singleton
Real-world examples
Use cases
Implementation
Summary
The Adapter Pattern
Real-world examples
Use cases
Implementation
Summary
The Decorator Pattern
Real-world examples
Use cases
Implementation
Summary
The Bridge Pattern
Real-world examples
Use cases
Implementation
Summary
The Facade Pattern
Real-world examples
Use cases
Implementation
Summary
Other Structural Patterns
The flyweight pattern
Real-world examples
Use cases
Implementation
The model-view-controller pattern
Real-world examples
Use cases
Implementation
The proxy pattern
Real-world examples
Use cases
Implementation
Summary
The Chain of Responsibility Pattern
Real-world examples
Use cases
Implementation
Summary
The Command Pattern
Real-world examples
Use cases
Implementation
Summary
The Observer Pattern
Real-world examples
Use cases
Implementation
Summary
The State Pattern
Real-world examples
Use cases
Implementation
Summary
Other Behavioral Patterns
Interpreter pattern
Real-world examples
Use cases
Implementation
Strategy pattern
Real-world examples
Use cases
Implementation
Memento pattern
Real-world examples
Use cases
Implementation
Iterator pattern
Real-world examples
Use cases
Implementation
Template pattern
Real-world examples
Use cases
Implementation
Summary
The Observer Pattern in Reactive Programming
Real-world examples
Use cases
Implementation
A first example
A second example
A third example
A fourth example
Summary
Microservices and Patterns for the Cloud
The Microservices pattern
Real-world examples
Use cases
Implementation
A first example
A second example
The Retry pattern
Real-world examples
Use cases
Implementation
A first example
A second example, using a third-party module
A third example, using another third-party module
The Circuit Breaker pattern
Real-world examples
Use cases
Implementation
The Cache-Aside pattern
Real-world examples
Use cases
Implementation
Throttling
Real-world examples
Use cases
Implementation
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Python is an object-oriented scripting language that is used in a wide range of categories. In software engineering, a design pattern is a solution for solving software design problems. Although they have been around for a while, design patterns remain one of the hot topics in software engineering and are a good source of information 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 hunt 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 all 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 efficiently address commonly-faced problems and develop applications, and also be comfortable working on scalable and maintainable projects of any size.
This book is for intermediate Python developers. Prior knowledge of design patterns is not required to enjoy this book.
Chapter 1,The Factory Pattern, will teach you how to use the Factory design pattern (Factory Method and Abstract Factory) to initialize objects, and also covers 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 object creation process for cases typically composed of several related objects.
Chapter 3,Other Creational Patterns, will teach you how to handle other object creation situations with techniques such as creating a new object that is a full copy (hence, named clone) of an existing object, a technique offered by the Prototype pattern. You will also learn about the Singleton pattern.
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 Bridge Pattern, will teach you how to externalize an object's implementation details from its class hierarchy to another object class hierarchy. This chapter encourages the idea of preferring composition over inheritance.
Chapter 7,The Facade Pattern, will teach you how to create a single entry point to hide the complexity of a system.
Chapter 8,Other Structural Patterns, will teach you the Flyweight, Model-View-Controller and Proxy patterns. With the Flyweight pattern, you will learn to reuse objects from an object pool to improve the memory usage and possibly the performance of your applications. The Model-View-Controller (MVC) pattern is used in application development (desktop, web) to improve maintainability by avoiding mixing the business logic with the user interface. And with the Proxy pattern, you provide a special object that acts as a surrogate or placeholder for another object to control access to it and reduce complexity and/or improve performance.
Chapter 9,The Chain of Responsibility Pattern, will teach another technique to improve the maintainability of your applications by avoiding mixing the business logic with the user interface.
Chapter 10,The Command Pattern, will teach you how to encapsulate operations (such as undo, copy, paste) as objects, to improve your application. Among the advantages of this technique, the object that invokes the command is decoupled from the object that performs it.
Chapter 11,The Observer Pattern, will teach you how to send a request to multiple receivers.
Chapter 12,The State Pattern, will teach you how to create a state machine to model a problem and the benefits of this technique.
Chapter 13,Other Behavioral Patterns, will teach you, among several other advanced programming techniques, 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 14,The Observer Pattern in Reactive Programming, will teach you how to send a notification to the registered stakeholders of a stream of data (and events), whenever there is a state change.
Chapter 15, Microservices and Patterns for the Cloud, will teach you several system design patterns which are important with today's increasing adoption of Cloud-Native applications and microservices architectures. You will learn that you can split your application into functional and/or technical services that can be maintained and deployed more independantly, using microservices-oriented frameworks, containers, and other techniques. Since you rely more and more on remote services as part of an application (for example, an API), retry mechanisms are used in places where a call is possible to fail but, if retried more than once, it is more probable to succeed. As an addition to doing retries for fault-tolerance, you will learn how to use Circuit breakers, a technique to allow one subsystem to fail without destroying the entire system. In applications that rely heavily on accessing data from a data store, using the Cache-Aside pattern can improve the performance while reading data from the data store via caching. This pattern can be used for read and update operations of data to and from the data store. Last but not least, the chapter introduces the Throttling pattern, the concept where, based on a rate-limiting or alternative technique, you can control how users consume your API or your service and make sure the service does not get overwhelmed by one particular tenant.
Use a machine with a recent version of Windows, Linux or MacOS.
Install Python 3.6. Also, it is useful to know about advanced syntax and new syntax introduced in the Python 3 releases. You might also want to learn about idiomatic Python programming, by checkout out resources on Internet about the topic, if needed.
Install and use Docker on your machine, to easily install and run the RabbitMQ server needed to run the microservices examples for
Chapter 15
,
Microservices and Patterns for the Cloud
. If you choose to use the Docker installation method, which is more and more needed for many server software and services packaged as containers, you will find useful information here
https://hub.docker.com/_/rabbitmq/
as well as here
https://docs.nameko.io/en/stable/installation.html
.
You can download the example code files for this book from your account at www.PacktPub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visitwww.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
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.
Here is a quote about design patterns from the Gang of Four book:
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.
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 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.
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
Person
Form
(
forms
.
Form
):
name
forms
.
CharField
(
max_length
100
)
birth_date
forms
.
DateField
(
required
False
)
