Allows clients to treat individual objects and compositions of objects uniformally.
Composites allow you to work with a collection of objects similarly as you would work with the object itself. One idea behind this pattern is the ability to model an object so it can contain an item or other objects. Additionally, common functionalty can be performed either on the item or for the composition of objects.
This pattern is a little difficult to describe without using a concrete example, so we start by describing an interface called IActive as follows:
public interface IActive
{
bool IsRunning();
void Stop();
}
We now can create an infomration object which uses this interface as follows:
public class Element : IActive
{
private bool _IsRunning;
public bool IsRunning()
{
return _IsRunning;
}
public void Stop()
{
...
_IsRunning = false;
}
}
Up to now, nothing is different from our regular programming creating an object using an Interface. Now we can introduce the ElementComposition object.
public class ElementComposite : IActive
{
private IList _elements;
public bool IsRunning()
{
//this returns true if all elements are running
foreach( IActive e in _elements )
{
if ( e.IsRunning() == false )
return false;
}
//all elements appear to be running
return true;
}
public void Stop()
{
//this stops all the elements
foreach( IActive e in _elements )
{
e.Stop();
}
}
}
Notice the _elements collection can contain any IActive object and hence, a the composition can contain other compositions.