Book Image

Mastering Python Design Patterns

By : Sakis Kasampalis
Book Image

Mastering Python Design Patterns

By: Sakis Kasampalis

Overview of this book

Table of Contents (23 chapters)
Mastering Python Design Patterns
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
The Factory Pattern
Index

Preface

Design patterns

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

Note

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

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

As programming languages evolve, some design patterns such as Singleton become obsolete or even antipatterns [j.mp/jalfdp], others are built in the programming language (iterator), and new patterns are born (Borg/Monostate [j.mp/amdpp], [j.mp/wikidpc]).

Common misunderstandings about design patterns

There are a few misunderstandings about design patterns. One misunderstanding is that design patterns should be used right from the start when writing code. It is not unusual to see developers struggling with which pattern they should use in their code, even if they haven't first tried to solve the problem in their own way [j.mp/prsedp], [j.mp/stedp].

Not only is this wrong, but it is also against the nature of design patterns. Design patterns are discovered (in contrast to invented) as better solutions over existing solutions. If you have no existing solution, it doesn't make sense to look for a better one. Just go ahead and use your skills to solve your problem as best as you think. If your code reviewers have no objections and through time you see that your solution is smart and flexible enough, it means that you don't need to waste your time on struggling about which pattern to use. You might have even discovered a better design pattern than the existing one. Who knows? The point is do not limit your creativity in favor of forcing yourself to use existing design patterns.

A second misunderstanding is that design patterns should be used everywhere. This results in creating complex solutions with unnecessary interfaces and hierarchies, where a simpler and straightforward solution would be sufficient. Do no treat design patterns as a panacea because they are not. They must be used only if there is proof that your existing code "smells", and is hard to extend and maintain. Try thinking in terms of you aren't gonna need it (YAGNI [j.mp/c2yagni]) and Keep it simple stupid (KISS [j.mp/wikikis]). Using design patterns everywhere is as evil as premature optimization [j.mp/c2pro].

Design patterns and Python

This book focuses on design patterns in Python. Python is different than most common programming languages used in popular design patterns books (usually Java [FFBS04] or C++ [GOF95]). It supports duck-typing, functions are first-class citizens, and some patterns (for instance, iterator and decorator) are built-in features. The intent of this book is to demonstrate the most fundamental design patterns, not all patterns that have been documented so far [j.mp/wikidpc]. The code examples focus on using idiomatic Python when applicable [j.mp/idiompyt]. If you are not familiar with the Zen of Python, it is a good idea to open the Python REPL right now and execute import this. The Zen of Python is both amusing and meaningful.

What this book covers

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

Chapter 1, The Factory Pattern, will teach you how to use the Factory design pattern (Factory Method and Abstract Factory) to initialize objects, and cover the benefits of using the Factory design pattern instead of direct object instantiation.

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

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

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

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

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

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

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

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

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

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

Chapter 10, The Chain of Responsibility Pattern, will teach you how to send a request to multiple receivers.

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

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

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

Chapter 14, The State Pattern, will teach you how to create a state machine to model a problem and the benefits of this technique.

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

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

What you need for this book

The code is written exclusively in Python 3. Python 3 is, in many aspects, not compatible with Python 2.x [j.mp/p2orp3]. The focus is on Python 3.4.0 but using Python 3.3.0 should also be fine, since there are no syntax differences between Python 3.3.0 and Python 3.4.0 [j.mp/py3dot4]. In general, if you install the latest Python 3 version from www.python.org, you should be fine with running the examples. Most modules/libraries that are used in the examples are a part of the Python 3 distribution. If an example requires any extra modules to be installed, instructions on how to install them are given before presenting the related code.

Who this book is for

The audience of this book is Python programmers with an intermediate background and an interest in design patterns implemented in idiomatic Python. Programmers of other languages who are interested in Python can also benefit, but it's better if they first read some materials that explain how things are done in Python [j.mp/idiompyt], [j.mp/dspython].

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We will use two libraries that are part of the Python distribution for working with XML and JSON: xml.etree.ElementTree and json."

A block of code is set as follows:

   @property
   def parsed_data(self): 
       return self.data 

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

   @property
   def parsed_data(self): 
       return self.data

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

>>> python3 factory_method.py

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

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

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

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

Reader feedback

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

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

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

Customer support

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

Downloading the example code

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

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

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

Piracy

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

Please contact us at with a link to the suspected pirated material.

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

Questions

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