Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Python Application Development

You're reading from  Learning Python Application Development

Product type Book
Published in Sep 2016
Publisher Packt
ISBN-13 9781785889196
Pages 454 pages
Edition 1st Edition
Languages
Author (1):
Ninad Sathaye Ninad Sathaye
Profile icon Ninad Sathaye

Table of Contents (18) Chapters

Learning Python Application Development
Credits
Disclaimers
About the Author
About the Reviewer
www.PacktPub.com
Preface
1. Developing Simple Applications 2. Dealing with Exceptions 3. Modularize, Package, Deploy! 4. Documentation and Best Practices 5. Unit Testing and Refactoring 6. Design Patterns 7. Performance – Identifying Bottlenecks 8. Improving Performance – Part One 9. Improving Performance – Part Two, NumPy and Parallelization 10. Simple GUI Applications Index

Chapter 6. Design Patterns

This chapter will introduce you to some commonly used design patterns. Here is how the chapter is organized:

  • We will start with a quick introduction to design patterns, followed by a discussion on some Python language features that help to simplify their implementation.

  • Next, with the help of a fantasy game theme, we will discuss the following design patterns:

    • Strategy pattern

    • Simple and abstract factory pattern

    • Adapter pattern

  • For each pattern, a simple game scenario will demonstrate a practical problem. We will see how the design pattern can help solve this problem.

  • We will also implement each of these patterns using a Pythonic approach.

There are several known design patterns out there. As outlined earlier, we will discuss only a few. The idea is not to present a new cookbook on patterns, but just to show you how design patterns help solve some commonly encountered problems, and how to implement them in Python. Beyond this book, you can explore other traditional design...

Introduction to design patterns


Let's say that during application development, you stumble upon a problem that pops up again and again. Frustrated, you ask your co-developers or a community for help. Guess what, you are not alone. Many have encountered a similar problem in their code. Luckily, you get a response from someone who has found a solution. This solution seemed to have worked reliably on similar problems. You change your problematic code so that it conforms to the suggested design, and voila! Your problem is resolved!

What we just discussed is a software design pattern. A software design pattern is a tried and tested solution or a strategy that helps us solve a commonly encountered problem in the code. Let's start with the broad categories of design patterns followed by some important design principles.

Note

The Gang of Four book:

Before beginning any discussion on the design patterns in Python, it is worth noting that there is an excellent book you may want on your bookshelf, Design...

Python language and design patterns


Thanks to the high-level built-in language features in Python, many of the formal design patterns are easy to implement. In some cases, the patterns appear so natural to the language that it becomes tough to realize them as formal design patterns. For example, an iterator pattern can be realized by using any iterable object, such as lists, dictionaries, and so on. Let's quickly review such language features or paradigms in this section. It is not an exhaustive list, but we will cover some important aspects.

Tip

The idioms that you are about to read (first-class functions, closures, and so on) might sound onerous. But do not get overwhelmed by these terms! If you are a Python programmer, it is very likely that you have already used many of these features knowingly or unknowingly. If these idioms mean nothing to you at the moment, skip ahead to the next section where we fast forward to an imaginary game scenario. In the upcoming discussion, we will use some...

Structure of the rest of the chapter


Before diving into the discussion on design patterns and their implementation, let's first lay out a strategy for the rest of the discussion. As mentioned before, we will review the strategy pattern, the simple and abstract factory patterns, and the adapter pattern. The discussion on design patterns will be roughly structured as follows:

  • Start with a formal definition of the pattern

  • Present an imaginary scenario where a new feature is requested

  • Talk about the problem encountered in introducing this new feature

  • Make an attempt to solve this problem, quickly realizing that we need to rethink the design

  • The solution(s) to the problem using the design pattern

For a few design patterns, we will discuss two approaches to solving the problem. A traditional approach that resembles the one followed in languages like C++, and the other, the Pythonic approach.

Tip

Skip the traditional solution if you are interested only in the Pythonic approach.

The following is a list of...

Fast forward – Attack of the Orcs v6.0.0


Let's fast forward to a future imaginary version of the game!

This imaginary version is one of the most downloaded open source Python applications. Now you have a team of developers helping you with application development. The game has evolved quite a bit. It is no longer a simple application where you gain control of a hut by defeating the enemy. It is now a turn-based fantasy game, where the player and the enemy take turns attacking each other, or use that turn to move towards or away from the opponent.

You have introduced several new game missions, and have redesigned and refactored the code to accommodate the new requirements. In the most recent version, you have the following game characters: Knight, Orc Rider, and Elf Rider.

Tip

An Elf is an imaginary supernatural mythical being. Read the The theme of the book section in Chapter 1, Developing Simple Applications for some references on Elves.

Each game character in this version has an ability...

Strategy pattern


A strategy design pattern is a behavioral pattern that is used to represent a family of algorithms. An algorithm within such a family is represented as a strategy object. The pattern enables easy switching between different strategies (algorithms) of a particular family. This is generally useful when you want to switch to a different strategy at runtime. We will revisit this definition towards the end of the discussion on strategy pattern.

Strategy scenario – The jump feature

There is a high priority feature request. Rather, it is a complaint. The users just hate the movement restriction imposed by the fence. Now even Sir Foo has joined the protest...

Rather than removing the fence from the scenario, how about a new feature that enables units to jump over the fence or any similar obstacle?

You have introduced a new method, jump(), in the superclass AbstractGameUnit. All the classes inherit this method, as shown in the following class diagram:

The fence no longer prevents...

Simple factory


A simple factory is generally not viewed as a formal design pattern, but you will find it quite useful in your day-to-day programming. The understanding we gain at the end of this section will be helpful in the discussion on a more formal pattern called abstract factory design pattern. Let's start with the definition of a simple factory.

A factory encapsulates the instance creation piece. The client code doesn't need to know the logic of instance creation. It just knows that whenever it needs an object of a specific type, the factory is the go-to place. Any class, or function, or class method that is used to construct such objects is often referred to as a factory. A simple factory is something you will use quite often. It is typically considered a better object-oriented technique than a formal design pattern.

Simple factory scenario – The recruit feature

Abstract factory pattern


We have just learned how to create and use a simple factory in a program. Let's go a little further and study a formal pattern known as the abstract factory pattern.

Imagine we have a master factory and some follower factories. Further assume that each follower factory is responsible for producing its own trademark products (objects). The follower factories are related in some sense. They create products that share a common theme. For example, each follower factory produces its own version of tomato ketchup. The factories have their own ordering form for their product.

The customers have a hard time in keeping up with so many forms for ordering a tomato ketchup. For example, one factory says you should call it MyRedTomatoKetchup, otherwise it won't understand. So, the master factory says:

Recall that we had fast-forwarded the game to an imaginary future version called Attack of the Orcs v6.0.0. This version...

Adapter pattern


The adapter design pattern enables a handshake between two incompatible interfaces. Here, the incompatible interface of a class or a library is transformed into the one expected by your client code. This transformation is accomplished by an adapter class. The other class with a different interface than what the client expects is often referred to as an adaptee.

There are two broad categories of adapter pattern, namely a class adapter pattern and an object adapter pattern. In the former, the adapter inherits from the adaptee. It is possible to implement a class adapter in Python, as the language supports multiple inheritance. However, it is better to choose object composition (has a relationship) over inheritance. In the object adapter pattern, the adapter object has an adaptee object instead of inheriting from the adaptee class. The object adapter pattern helps maintain a loose coupling between the adaptee and the client code, wherein the client does not need to have any knowledge...

Summary


This chapter provided an introduction to design patterns in Python, an important aspect of application development. We started this chapter with an introduction and saw how design patterns are classified. Next we reviewed some key features offered by the Python language that help simplify several design patterns. With practical illustrations, you learned how design patterns can be implemented to provide a solution to recurring problems in application development. More specifically, you learned about strategy, abstract factory, and adapter patterns. For each of these patterns, we first used an interesting game scenario to describe the problem. We then discussed how the design pattern can tackle this problem, and further implemented the design pattern using a Pythonic approach. For some patterns, we also reviewed a traditional approach to implementing the design pattern. Last but not the least, we met some of Sir Foo's new friends.

So far, we have discussed several important aspects...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learning Python Application Development
Published in: Sep 2016 Publisher: Packt ISBN-13: 9781785889196
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}

We make products that are like a part of an extended family. Our customers would benefit if we can simplify and standardize the procedure to order these products from our group of...