Summary

In this chapter, we took a detailed tour of object-oriented design patterns, and found out new and different ways to implement them in Python. We started with an overview of design patterns and their classification into Creational, Structural, and Behavioral patterns.

We went on to see an example of a Strategy design pattern, and saw how to implement this in a Pythonic manner. We then began our formal discussion of patterns in Python.

In Creational patterns, we covered the Singleton, Borg, Prototype, Factory, and Builder patterns. We saw why Borg is usually a better approach than Singleton in Python due to its ability to keep state across class hierarchies. We saw the interplay between the Builder, Prototype, and Factory patterns, and saw a few examples. Everywhere possible, metaclass discussions were introduced, and pattern implementations were done using metaclasses.

In Structural patterns, our focus was on the Adapter, Facade, and Proxy patterns. We saw detailed examples using the Adapter pattern, and discussed approaches via inheritance and object composition. We saw the power of magic methods in Python when we implemented the Adapter and Proxy patterns via the __getattr__ technique.

In Facade, using a Car class, we saw a detailed example on how Facade helps programmers conquer complexity and provide generic interfaces over the subsystems. We also saw that many Python standard library modules are themselves facades.

In the Behavioral section, we discussed the Iterator, Observer, and State patterns. We saw how iterators are part and parcel of Python. We implemented an iterator as a generator for building Prime numbers.

We saw a simple example of the Observer pattern by using an Alarm class as a Publisher and a clock class as Subscriber. We also saw an example of an asynchronous observer pattern using the asyncio module in Python.

Finally, we ended our discussion of patterns with the State pattern. We discussed a detailed example, switching the states of a computer through allowable state changes, and how one can use Python's __class__ as a dynamic attribute to change the class of an instance. In the implementation of State, we borrowed techniques from the Iterator pattern, and implemented the State example class as an Iterator.

In our next chapter, we move on from design to the next-higher paradigm of patterns in software architectures: architectural patterns.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.14.245