Book Image

Learning Python Design Patterns - Second Edition - Second Edition

By : Chetan Giridhar, Gennadiy Zlobin
Book Image

Learning Python Design Patterns - Second Edition - Second Edition

By: Chetan Giridhar, Gennadiy Zlobin

Overview of this book

With the increasing focus on optimized software architecture and design it is important that software architects think about optimizations in object creation, code structure, and interaction between objects at the architecture or design level. This makes sure that the cost of software maintenance is low and code can be easily reused or is adaptable to change. The key to this is reusability and low maintenance in design patterns. Building on the success of the previous edition, Learning Python Design Patterns, Second Edition will help you implement real-world scenarios with Python’s latest release, Python v3.5. We start by introducing design patterns from the Python perspective. As you progress through the book, you will learn about Singleton patterns, Factory patterns, and Façade patterns in detail. After this, we’ll look at how to control object access with proxy patterns. It also covers observer patterns, command patterns, and compound patterns. By the end of the book, you will have enhanced your professional abilities in software architecture, design, and development.
Table of Contents (19 chapters)
Learning Python Design Patterns Second Edition
Credits
Foreword
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

The Monostate Singleton pattern


We discussed the Gang of Four and their book in Chapter 1, Introduction to Design Patterns. GoF's Singleton design pattern says that there should be one and only one object of a class. However, as per Alex Martelli, typically what a programmer needs is to have instances sharing the same state. He suggests that developers should be bothered about the state and behavior rather than the identity. As the concept is based on all objects sharing the same state, it is also known as the Monostate pattern.

The Monostate pattern can be achieved in a very simple way in Python. In the following code, we assign the __dict__ variable (a special variable of Python) with the __shared_state class variable. Python uses __dict__ to store the state of every object of a class. In the following code, we intentionally assign __shared_state to all the created instances. So when we create two instances, 'b' and 'b1', we get two different objects unlike Singleton where we have just...