A software example

Python's sorted() and list.sort() functions are examples of the Strategy pattern. Both functions accept a named parameter key, which is basically the name of the function that implements a sorting Strategy [Eckel08, page 202].

The following example (the code is in the langs.py file) shows how two different strategies can be used to sort programming languages in the following ways:

  • Alphabetically
  • Based on their popularity (using the TIOBE index [j.mp/tiobe14])

A namedtuple programming language [j.mp/namedtuple] is used to keep the statistics of the programming languages. A named tuple is an easy-to-create, lightweight, immutable object type. It is compatible with a normal tuple but it can also be treated as an object (can be called ...

Get Mastering Python Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.