36 const int NAME_PADDING_SIZE = 20;
37 StringBuilder output =
new StringBuilder();
38 string spaces =
new string(
' ', depth * 2);
39 output.AppendFormat(
"{0}{1}", spaces, entry.
Name);
40 int padding = NAME_PADDING_SIZE - entry.Name.Length - (depth * 2);
46 output.AppendFormat(
"{0}",
new string(
' ', padding));
47 output.AppendFormat(
"{0,4}", entry.
Length);
48 output.AppendFormat(
" {0}", entry.
WhenModified.ToString());
49 output.AppendFormat(
"{0}", Environment.NewLine);
54 for (
int index = 0; index < children.
Length; ++index)
60 return output.ToString();
72 Console.WriteLine(output);
83 Console.WriteLine(
"Composite Exercise");
86 string filepath =
"root";
88 Console.WriteLine(
" Showing object '{0}'", filepath);
91 filepath =
"root/subdir1/FileD.txt";
93 Console.WriteLine(
" Showing object '{0}'", filepath);
96 catch (System.IO.FileNotFoundException e)
98 Console.WriteLine(
"{0}: {1}", e.GetType().Name, e.Message);
100 Console.WriteLine(
" Done.");
Example of using the Composite Pattern in C#.
void Run()
Executes the example for the Composite Pattern in C#.
string Composite_Exercise_FormatEntry(FileDirEntry entry, int depth)
Format the specified entry for display.
void Composite_Exercise_ShowEntry(FileDirEntry entry)
Recursively display the contents of the hierarchical list of objects starting with the given object.
Static class containing functions for accessing a hardcoded "file" and "directory" hierarchy.
static FileDirEntry GetEntry(string filepath)
Return a FileDirEntry object representing the specified file "path" in an internal list of data entri...
Base class representing a File or Directory entry.
virtual long Length
The length in bytes of this entry. Directory entries are the sum of the length of all children.
virtual ? FileDirEntry[] Children
The children of this entry. Is null if the entry can never have any children (that is,...
virtual DateTime WhenModified
When this entry was last modified.
virtual string Name
The name of this entry.
virtual FileDirTypes FileDirType
The type of this entry as represented by a value from the FileDirTypes enumeration.
The namespace containing all Design Pattern Examples implemented in C#.
FileDirTypes
Represents the type of entries allowed in the hierarchy for the Composite design pattern example.