19.6. Object-oriented design patterns

Presenting Python classes and various related mechanisms without any description of their common uses would be like defining the for and while statements without any description of the typical uses of these constructions, and how they adapt to various programming needs. It is the purpose of this section to present common uses of classes and objects, the so-called design patterns, that have been used for a long time by programmers since object-oriented programming was born.

Computer science is full of design patterns, and there is no exception for object-oriented programming. A catalog of object-oriented has been published by [Gamma95], and [Christopher2002] has a chapter dedicated to a few of them, with examples implemented in Python. Design patterns are not programs: they are widely used design choices to build programs. As such, they form a kind of conceptual catalog that you are encouraged to reuse to build your application. Not only are they useful in order not to reinvent the wheel and to save your time, but also because they provide a comprehension framework for programmers who intend to reuse your code and who need to understand it. This part does not aim at an exhaustive presentation of object-oriented design patterns, which are very well described elsewhere. Its main purpose is to give a taste of it, with examples in bioinformatics, and to introduce the main related ideas.

There are three categories of object-oriented patterns:

Creational patterns.  There are two main categories of creational patterns: those for creating objects without having to know the class name, that you could call "abstract object makers" (abstract factory and factory method), and those to ensure a certain property regarding object creation, such as prohibiting more than one instance for a class (singleton), building a set of instances from different classes in a consistent way (builder), or creating an instance with a specific state (prototype).

Structural patterns.  Structural patterns address issues regarding how to combine and structure objects. For this reason, several structural patterns provide alternative solutions to design problems that would else involve inheritance relationships between classes.

Behavioral patterns.  Patterns of this category are very useful in sequence analysis, where you often have to combine algorithms and to analyze complex data structure in a flexible way.