Composite Pattern Code Review

Use the Composite Pattern

Code Download

  • Download Description:composite pattern download
  • .NET Framework:3.5
  • .NET Language:C#
  • Date Published:2009-07-01
  • Download Size:22 KB

Code Walkthrough

Define the IComponent interface to be used as the "blueprint" for the composite and component classes.

public interface IComponent { Boolean Add(IComponent component); Boolean Remove(IComponent component); IComponent Find(String name); String Display(); String Name { get; set; } }

The Album class (object) inherits from the IComponent interface and represents the composite component. This class contains a list of IComponent components.

public class Album : IComponent { public String Name { get; set; } public List<IComponent> Photos { get; private set; }
public Album(String name) { this.Name = name; this.Photos = new List<IComponent>(); }
public bool Add(IComponent component) { this.Photos.Add(component); return (true); } public bool Remove(IComponent component) { IComponent componentFound;
componentFound = this.Find(component.Name);
if (componentFound != null) { this.Photos.Remove(componentFound); return (true); } else { return (false); } } public IComponent Find(String name) { return this.Photos.Find(delegate(IComponent component) { return (component.Name == name); } ); } public string Display() { StringBuilder sb = new StringBuilder(); foreach (IComponent component in this.Photos) { sb.Append(String.Format("Photo: {0}\n", component.Name)); } return(sb.ToString()); } }

The Photo class (object) inherits from the IComponent interface and represents a single component.

class Photo : IComponent { public String Name { get; set; }
public Photo(String name) { this.Name = name; }
public bool Add(IComponent component) { throw new Exception("Cannot add to a Photo."); } public bool Remove(IComponent component) { throw new Exception("Cannot remove Photo directly."); } public IComponent Find(string name) { throw new Exception("Cannot find a Photo."); } public string Display() { return (String.Format("The name of the photo is {0}.", this.Name)); }
public override string ToString() { return this.Name; } }