Composite Design Pattern

Introduction:
Sometimes you want to treat a group of objects as a single instance. Composite design pattern is aiming to compose object into a structure of tree to represent part-whole hierarchy structures.
A simple example of this design pattern is directory structure.. Each directory might contains some entries and those entries might be a directory. Which leads us to a tree hierarchy structure.
Example:

CompositeDesignPattern

 

class Program
{
static void Main(string[] args)
{
Directory dir = new Directory(“c:”);
dir.Add(new File(“File 1”));
dir.Add(new File(“File 2”));
Directory dir2 = new Directory(“Program Files”);
dir2.Add(new File(“Program 1”));
dir2.Add(new File(“Program 2”));
dir.Add(dir2);
dir.Display(0,0);
Console.ReadKey();
}
}
abstract class DirectoryEntry
{
protected string name;
// Constructor
public DirectoryEntry(string name)
{
this.name = name;
}
public abstract void Add(DirectoryEntry entry);
public abstract void Remove(DirectoryEntry entry);
public abstract void Display(int depth,int leadingSpaces);
}
class File : DirectoryEntry
{
public File(string name ) :base(name)
{
}
public override void Add(DirectoryEntry entry)
{
Console.WriteLine(“Cannot add to a File”);
}
public override void Remove(DirectoryEntry entry)
{
Console.WriteLine(“Cannot remove from a File”);
}
public override void Display(int depth, int leadingSpaces)
{
Console.WriteLine(new string(‘ ‘, leadingSpaces) +  “|” + new String(‘-‘, depth) + name);
}
}
class Directory : DirectoryEntry
{
private List<DirectoryEntry> _children = new List<DirectoryEntry>();
public Directory(string name) : base(name)
{
}
public override void Add(DirectoryEntry entry)
{
_children.Add(entry);
}
public override void Remove(DirectoryEntry entry)
{
_children.Remove(entry);
}
public override void Display(int depth, int leadingSpaces)
{
Console.WriteLine( new string(‘ ‘ , leadingSpaces) + “|” + new string(‘-‘ ,  depth)  + name);
// Recursively display child nodes
foreach (DirectoryEntry entry in _children)
{
entry.Display(depth + 2, leadingSpaces+2);
}
}
}

 

Download Code

Leave a Reply

Your email address will not be published.