Design Patterns in Python Cheat Sheet
This cheat sheet was created using the “Design Patterns In Python” course. This is a one page medium sized article to remember. I highly recommend this course. After studying this course it will be useful to read this cheat sheet. I plan to add hand-drawn images to help memorise these pattern examples. If you want to have more details with source codes, you should follow the link.
UML Diagrams








Creational -> Factory Design Pattern
Abstraction between the creation of an object and where it is used.

An example use case is a user interface where the user can select from a menu of items, such as chairs.
The user has been given a choice using some kind of navigation interface, and it is unknown what choice, or how many the user will make until the application is actually running, and the user starts using it.
So, when the user selected the chair, the factory then takes some property involved with that selection, such as an ID, Type or other attribute and then decides which relevant subclass to instantiate in order to return the appropriate object.

Creational -> Abstract Factory Design Pattern
Adds an abstraction over many other related objects that are created using other creational patterns.

An example use case may be that you have a furniture shopfront. You sell many kinds of furniture. You sell chairs and tables. And they are manufactured at different factories using different unrelated processes that are not important for your concern. You only need the factory to deliver.
You can create an extra module called FurnitureFactory, to handle the chair and table factories, thus removing the implementation details from the client.

Creational -> Builder Design Pattern
A creational pattern whose intent is to separate the construction of a complex object from its representation so that you can use the same construction process to create different representations.

Using the Builder Pattern in the context of a House Builder.
There are multiple directors that can create their own complex objects.
Note that in the IglooDirector class, not all the methods of the HouseBuilder were called.
The builder can construct complex objects in any order and include/exclude whichever parts it likes.

Creational -> Prototype Design Pattern
Good for when creating new objects requires more resources than you need of have available.

In this example, an object called document is cloned using shallow, 2 level shallow, and full recursive deep methods.
The object contains a list of two lists. Four copies are created, and each time some part of the list is changed on the clone, and depending on the method used, it can affect the original object.
When cloning an object, it is good to understand the deep versus shallow concept of copying.

Creational -> Singleton Design Pattern
A class that can be instanced at any time, but after it is first instanced, any new instances will point to the original instance.

In the example, there are three games created. They are all independent instances created from their own class, but they all share the same leaderboard. The leaderboard is a singleton.
It doesn’t matter how the Games where created, or how they reference the leaderboard, it is always a singleton.
Each game independently adds a winner, and all games can read the altered leaderboard regardless of which game updated it.

Structural -> Decorator Design Pattern
Attach additional responsibilities to an object at runtime.

Let’s create a custom class called Value that will hold a number.
Then add decorators that allow addition (Add) and subtraction (Sub) to a number (Value).
The Add and Sub decorators can accept integers directly, a custom Value object or other Add and Sub decorators.
Add, Sub and Value all implement the IValue interface and can be used recursively.

Structural -> Adapter Design Pattern
An alternative interface over an existing interface.

The example client can manufacture a Cube using different tools. Each solution is invented by a different company. The client user interface manages the Cube product by indicating the width, height and depth. This is compatible with the company A that produces the Cube tool, but not the company B that produces their own version of the Cube tool that uses a different interface with different parameters.
In this example, the client will re-use the interface for company A’s Cube and create a compatible Cube from company B.
An adapter will be needed so that the same method signature can be used by the client without the need to ask company B to modify their Cube tool for our specific domains use case.
My imaginary company needs to use both cube suppliers since there is a large demand for cubes and when one supplier is busy, I can then ask the other supplier.

Structural -> Facade Design Pattern
An alternative or simplified interface over other interfaces.

This is an example of a game engine API. The facade layer is creating one streamlined interface consisting of several methods from several larger API backend systems.
The client could connect directly to each subsystem’s API and implement its authentication protocols, specific methods, etc. While it is possible, it would be quite a lot of consideration for each of the development teams, so the facade API unifies the common methods that becomes much less overwhelming for each new client developer to integrate into.

Structural -> Bridge Design Pattern
The Bridge pattern is similar to the Adapter pattern except in the intent that you developed it.

In this example, I draw a square and a circle. Both of these can be categorized as shapes.
The shape is set up as the abstraction interface. The refined abstractions, Square and Circle, implement the IShape interface.
When the Square and Circle objects are created, they are also assigned their appropriate implementers being SquareImplementer and CircleImplementer.
When each shape’s draw method is called, the equivalent method within their implementer is called.
The Square and Circle are bridged and each implementer and abstraction can be worked on independently.

Structural -> Composite Design Pattern
A structural pattern useful for hierarchical management.

Demonstration of a simple in memory hierarchical file system.
A root object is created that is a composite.
Several files (leaves) are created and added to the root folder.
More folders (composites) are created, and more files are added, and then the hierarchy is reordered.

Structural -> Flyweight Design Pattern
Share objects rather than creating thousands of near identical copies.

In this example, I create a dynamic table with 3 rows and 3 columns each. The columns are then filled with some kind of text, and also chosen to be left, right or center aligned.
The letters are the flyweights and only a code indicating the letter is stored. The letters and numbers are shared many times.
The column cells are the contexts, and they pass the extrinsic vales describing the combination of letters, the justification left, right or center, and the width of the table column that is then used for the space padding.

Structural -> Proxy Design Pattern
A class functioning as an interface to another class or object.

In this example, I dynamically change the class of an object. So, I am essentially using an object as a proxy to other classes.
Every time the tell_me_the_future() method is called; it will randomly change the object to use a different class.
The object PROTEUS will then use the same static attributes and class methods of the new class instead.

Behavioural -> Command Design Pattern
An abstraction between an object that invokes a command, and the object that performs it. Useful for UNDO/REDO/REPLAY.

This will be a smart light switch.
This light switch will keep a history of each time one of its commands was called.
And it can replay its commands.
A smart light switch could be extended in the future to be called remotely or automated depending on sensors.

Behavioural -> Chain of Responsibility
Pass an object through a chain of successor handlers.

In the ATM example below, the chain is hard coded in the client first to dispense amounts of £50s, then £20s and then £10s in order.
This default chain order helps to ensure that the minimum number of notes will be dispensed. Otherwise, it might dispense 5 x £10 when it would have been better to dispense 1 x £50.

Behavioural -> Observer Design Pattern
Manage a list of dependents and notifies them of any internal state changes.

This example mimics the MVC approach described earlier.
There is an external process called a DataController, and a client process that holds a DataModel and multiple DataViews that are a Pie graph, Bar graph and Table view.
Note that this example runs in a single process, but imagine that the DataController is actually an external process running on a different server.
The DataModel subscribes to the DataController and the DataViews subscribe to the DataModel.
The client sets up the various views with a subscription to the DataModel.
The hypothetical external DataController then updates the external data, and the data then propagates through the layers to the views.
Note that in reality this example would be much more complex if multiple servers are involved. I am keeping it brief to demonstrate one possible use case of the observer pattern.
Also note that in the DataController, the references to the observers are contained in a Set, while in the DataModel I have used a Dictionary instead, so that you can see an alternate approach.

Behavioural -> Interpreter Design Pattern
Convert information from one language to another.

The example use case will expand on the concept example by dynamically creating the AST and converting Roman numerals to integers as well as calculating the final result.
The Image below, is an AST for the expression 5 + IV - 3 + VII - 2


Behavioural -> Iterator Design Pattern
Traverse a collection of aggregates.

One reason for not using the inbuilt Python data structures that implement iterators already, or using the iter function directly over an existing collection, is in the case when you want to create an object that can dynamically create iterated objects, you want a custom order of objects or an infinite iterator.
The iterator in this brief example will return the next number in the iterator multiplied by 2 modulus 11. It dynamically creates the returned object (number) at runtime.
It has no has_next() method since the result is modulated by 11, that will loop the results no matter how large the iterator index is. Furthermore, it will also appear to alternate between a series of even numbers and odd numbers.
Also, just to demonstrate that implementing abstract classes and interfaces is not always necessary, this example uses no abstract base classes or interfaces.

Behavioural -> Mediator Design Pattern
Objects communicate through a Mediator rather than directly with each other.

In this example use case, we will implement some behavior into the mediation process.
Before the mediation logic is added, consider that the below example is a series of components all subscribed to a central location being the subject. They all implement the Observer pattern.
Each component is updated independently by external forces, but when it has new information, it notifies the subject which in turn then notifies the other subscribed components.
During the synchronization of all the subscribed components, without the extra mediation, the component that provided the new information will receive back the same message that it just notified the subject of. In order to manage the unnecessary duplicate message, the notifications will be mediated to exclude to component where the original message originated from.

Behaviour -> Memento Design Pattern
Save a copy of state and for later retrieval. Useful for UNDO/REDO/LOAD/SAVE.

There is a game, and the character is progressing through the levels. It has acquired several new items in its inventory, the score is very good, and you want to save your progress and continue later.
You then decide you made a mistake and need to go back to a previous save because you took a wrong turn.

Behavioural -> State Design Pattern
Alter an objects behavior by changing the handle of one of its methods to one of its subclasses dynamically to reflect its new internal state.

This example takes the concept example further and uses an iterator rather than choosing the states subclasses randomly.
When the iterator gets to the end, it raises a StopIteration error and recreates the iterator so that the process can loop again.

Behavioural -> Strategy Design Pattern
Similar to the State Pattern, except that the client passes in the algorithm that the context should then run.

A game character is moving through an environment. Depending on the situation within the current environment, the user decides to use a different movement algorithm. From the perspective of the object/context, it is still a move, but the implementation is encapsulated in the subclass at the handle.
In a real game, the types of things that a particular move could affect is which animation is looped, the audio, the speed, the camera follow mode and more.

Behavioural -> Template Design Pattern
An abstract class (template) that contains a method that is a series of instructions that are a combination of methods that can be overridden.

In the example use case, there is an AbstractDocument with several methods, some are optional and others must be overridden.
The document will be written out in two different formats.
Depending on the concrete class used, the text() method will wrap new lines with <p> tags and the print() method will format text with tabs, or include HTML tags.

Behavioural -> Visitor Design Pattern
Pass an object called a visitor to a hierarchy of objects and execute a method on them.

In the example, the client creates a car with parts.
The car and parts inherit an abstract car parts class with predefined property getters and setters.
Instead of creating methods in the car parts classes and abstract class that run bespoke methods, the car parts can all implement the IVisitor interface.
This allows for the later creation of Visitor objects to run specific tasks on the existing hierarchy of objects.





