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

A real-life example


Once again (we saw this in the Chain of Responsibility pattern), a snack vending machine is an example of the State pattern in everyday life. Vending machines have different states and react differently depending on the amount of money that we insert. Depending on our selection and the money we inserted, the machine can:

  • Reject our selection because the product we requested is out of stock

  • Reject our selection because the amount of money we inserted is not sufficient

  • Deliver the product and give no change because we inserted the exact amount

  • Deliver the product and return the change

There are, for sure, more possible states, but you get the point. The following figure, provided by www.sourcemaking.com [j.mp/smstate], shows a possible implementation of the different vending machine states using inheritance: