2007 |
Section 3, Chapter 4 |
Composite Pattern
Concept
The Composite pattern allows you to compound different subsets of functionality into a collection and then call each subset in turn in the collection at a given point.
Use
You had a collection of objects, and each object had a particular method that you wanted to call in series.
Design
A composite allows you to call the classes with a single method and loop through the collection, calling the method on each class.
- Component - The base class with the common functionality for all classes.
- Leaf - the object that makes up the individual objects that exist within the collection.
- Composite - the class that forms the collection object itself.
Both the leaf and the composite classes inherit from the component, so that whether you call the individual leaf classes or the composite class, you still call the same method(s).
Illustration
//Component
abstract class Component
{
private string _name;
public Component(string name)
{
_name = name;
}
public string Name
{
get{return _name;}
}
public abstract void Draw();
public override int GetHashCode()
{
return _name.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj != null && obj is Component)
return _name.Equals(((Component)obj).Name);
else
return false;
}
public override string ToString()
{
return _name;
}
}
//Leaf
class GraphicalComponent : Component
{
public GraphicalComponent(string name) : base(name){}
public override void Draw()
{
......
}
}
//composite
class GraphicalComposite : Component
{
private ArrayList _children = new ArrayList();
public GraphicalComposite(string name) : base(name){}
public void Add(Component child)
{
_children.Add(child);
}
public void Remove(Component child)
{
_children.Remove(child);
}
public Component GetChild(int index)
{
return (Component)_children[index];
}
public override void Draw()
{
foreach(Component comp in _children)
comp.Draw();
}
}
GraphicalComposite root = new GraphicalComposite("OuterPanel");
root.Add(new GraphicalComponent("Circle"));
root.Add(new GraphicalComponent("Square"));
root.Add(new GraphicalComponent("Triangle"));
GraphicalComposite childComposite = new GraphicalComposite("InnerPanel");
childComposite.Add(new GraphicalComponent("Line"));
root.Add(childComposite);
GraphicalComponent removable = new GraphicalComponent("Single Line");
root.Add(removable);
root.Remove(removable);
A composite class can also contain other composite classes.
You can have a two-sided relationship, which means the leaf objects know about their parent composite object.