Design Pattern Examples
Overview of object-oriented design patterns
composite_exercise.py
Go to the documentation of this file.
6
7from io import StringIO
8
9from .composite_filedirentry import FileDirEntry, FileDirTypes, FileDirEntryList
10from .composite_fileaccess import Composite_FileAccess
11
12
22def Composite_Exercise_FormatEntry(entry : FileDirEntry, depth : int) -> str:
23 NAME_PADDING_SIZE = 20
24 output = StringIO()
25 spaces = ' ' * (depth * 2)
26 output.write("{0}{1}".format(spaces, entry.Name))
27 padding = NAME_PADDING_SIZE - len(entry.Name) - (depth * 2)
28 if entry.FileDirType == FileDirTypes.Directory:
29 output.write("/")
30 padding -= 1
31 output.write(' ' * padding)
32 output.write("{0:4}".format(entry.Length))
33 output.write(" {0}".format(entry.WhenModified.strftime("%m/%d/%Y %I:%M:%S %p")))
34 output.write("\n")
35
36 children = entry.Children
37 if children:
38 for index in range(0, len(children)):
39 output.write(Composite_Exercise_FormatEntry(children[index], depth + 1))
40
41 return output.getvalue()
42
43
44
45
50def Composite_Exercise_ShowEntry(entry : FileDirEntry) -> None:
51 output = Composite_Exercise_FormatEntry(entry, 2)
52 print(output)
53
54
55
64
65# ! [Using Composite in Python]
67 print()
68 print("Composite Exercise")
69
70 try:
71 filepath = "root"
72 rootEntry = Composite_FileAccess.GetEntry(filepath)
73 print(" Showing object '{}'".format(filepath))
75
76 filepath = "root/subdir1/FileD.txt"
77 rootEntry = Composite_FileAccess.GetEntry(filepath)
78 print(" Showing object '{}'".format(filepath))
80 except FileNotFoundError as ex:
81 print("Error! {} ".format(ex))
82
83 print(" Done.")
84# ! [Using Composite in Python]
str Composite_Exercise_FormatEntry(FileDirEntry entry, int depth)
Format the specified entry for display.
def Composite_Exercise()
Example of using the Composite Pattern.
None Composite_Exercise_ShowEntry(FileDirEntry entry)
Recursively display the contents of the hierarchical list of objects starting with the given object.