Saturday, May 30, 2015

Use Python to Explain Adapter of Design Pattern

The Adapter is described in the Design Pattern book. Please refer the book for the details. A better way to learn Design Pattern is to program it by yourself. Python is a good language because it supports class and is easy to program than C++. That is why I select it to practice Design Pattern.

This page uses Python to implement an Adapter that displays a directory tree.

TreeDisplay is an abstract class that has two abstract methods GetChildren() and CreateGraphicNode(). The sample uses raise in both abstract methods to notify a programmer that the both are abstract that must be implemented in a derived class.

DirectoryTreeDisplay1 is an Adapter that adapts Python OS package (Adaptee). GetChildren() uses Python OS package to get directory tree. CreateGraphicNode() transforms directory tree to readable text.

Test1() is a test function that tests DirectoryTreeDisplay1 ()

Below is a results after running the Python program in MacBook.
$ python ./DesignPattern/Adapter/

The style of the directory tree is not good. A new Adapter, DirectoryTreeDisplay2, refines the style.

Test2() tests the new Adapter.

The better style of the directory tree displays as below after running the Python program.

The below class diagram summarizes the implementation.


No comments:

Post a Comment