Mastering Python Design Patterns. - Kamon Ayeva - E-Book

Mastering Python Design Patterns. E-Book

Kamon Ayeva

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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:

EPUB
MOBI

Seitenzahl: 266

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering Python Design PatternsSecond Edition
A guide to creating smart, efficient, and reusable software
Kamon Ayeva
Sakis Kasampalis
BIRMINGHAM - MUMBAI

Mastering Python Design Patterns Second Edition

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

To my parents, Catherine Ayeva and Paul Nassourou Ayeva, for their constant support and for having taught me the spirit of "always putting your best into it". And to my daughter Tiyi. Thanks to the friendly and hard-working team at Packt that I worked with for this book. It was a really nice experience.
– Kamon Ayeva
mapt.io

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.

Why subscribe?

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

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [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.

Contributors

About the authors

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.

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

About the reviewer

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.

To my wife, Shuby Arora, and my angel (daughter), Aarchi Arora, who permitted me to steal time for this book from the time I was supposed to spend with them. Thanks to the entire Packt team, especially Ulhas, Vikas Tiwari, Anugraha Arunagiri, and Jash Bavishi, whose coordination and communication during the period was tremendous, and Denim Pinto, who introduced me for this book.

Packt is searching for authors like you

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.

Table of Contents

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

Preface

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.

Who this book is for

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

What this book covers

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.

To get the most out of this book

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

.

Download the example code files

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!

Get in touch

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.

Reviews

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.

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

Person

Form

(

forms

.

Form

):

name

forms

.

CharField

(

max_length

100

)

birth_date

forms

.

DateField

(

required

False

)