luni, 23 noiembrie 2009

[DesignPatterns] Composite Pattern

The Composite pattern arranges structured hierarchies so that single components and groups of components can be treated in the same way.
It has to deal with two types: Components and Composites of those components. Composite objects consist of Components.

Components:
- IComponent - default behavior for all object used in composition
- Component
- Composite - Implements the operations as applicable to composite objects. The Composite keeps as a list a local structure that consists of Components and Composites

Sample:
public interface IComponent {
void Add(IComponent c);
IComponent Remove(T s);
IComponent Find(T s);
string Display(int depth);
T Item {get; set;} }
// The Component
public class Component : IComponent {
public T Name {get; set;}
public Component (T name) { Name = name; }
public void Add(IComponent c) { Console.WriteLine("Cannot add to an item"); }
public IComponent Remove(T s) { Console.WriteLine("Cannot remove directly"); return this; }
public string Display(int depth) { return new String('-', depth) + Name+"\n"; }
public IComponent Find (T s) { if (s.Equals(Name)) return this; else return null; } }

// The Composite
public class Composite : IComponent {
List > list;
public T Name {get; set;}
public Composite (T name) { Name = name;
list = new List > ( ); }
public void Add(IComponent c) { list.Add(c); }
Component holder=null;
// Finds the item from a particular point in the structure
// and returns the composite from which it was removed
// If not found, return the point as given
public IComponent Remove(T s) { holder = this;
IComponent p = holder.Find(s);
if (holder!=null) { (holder as Composite).list.Remove(p); return holder; }
else return this; }
// Recursively looks for an item
// Returns its reference or else null
public IComponent Find (T s) { holder = this;
if (Name.Equals(s)) return this;
IComponent found=null;
foreach (IComponent c in list) {
found = c.Find(s);
if (found!=null) break; }
return found; }
// Displays items in a format indicating their level in the composite structure
public string Display(int depth) { StringBuilder s = new StringBuilder(new String('-', depth));
s.Append("Set "+ Name + " length :" + list.Count + "\n");
foreach (IComponent component in list) { s.Append(component.Display(depth + 2)); }
return s.ToString( ); } }
}

Niciun comentariu:

Trimiteți un comentariu