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


There is not much to be said about implementing the Strategy pattern. In languages where functions are not first-class citizens, each Strategy should be implemented in a different class. Wikipedia demonstrates that at [j.mp/stratwiki]. In Python, we can treat functions as normal variables and this simplifies the implementation of Strategy.

Assume that we are asked to implement an algorithm to check if all characters in a string are unique. For example, the algorithm should return true if we enter the string "dream" because none of the characters is repeated. If we enter the string "pizza", it should return false because the letter "z" exists two times. Note that the repeated characters do not need to be consecutive, and the string does not need to be a valid word. The algorithm should also return false for the string "1r2a3ae" because the letter "a" appears twice.

After thinking about the problem carefully, we come up with an implementation that sorts the string and compares...