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

Implementation


In this section, we will use the Command pattern to implement the most basic file utilities:

  • Creating a file and optionally writing a string in it

  • Reading the contents of a file

  • Renaming a file

  • Deleting a file

We will not implement these utilities from scratch, since Python already offers good implementations of them in the os module. What we want is to add an extra abstraction level on top of them so that they can be treated as commands. By doing this, we get all the advantages offered by commands.

The following use case diagram shows the supported operations that a user can execute. From the operations shown, renaming a file and creating a file support undo. Deleting a file and reading the contents of a file do no support undo. Undo can actually be implemented on delete file operations. One technique is to use a special trash/wastebasket directory that stores all the deleted files, so that they can be restored when the user requests it. This is the default behavior used on all...