
.NET 1.1+Composite Design Pattern (2)
The composite pattern is a design pattern that is used when creating hierarchical object models. The pattern defines a manner in which to design recursive tree structures of objects, where individual objects and groups can be accessed in the same manner.
Example Composite
Earlier in this article I mentioned that the composite design pattern could be used to create an object model that represents a company's management structure. In this section, we will create this example and demonstrate its use. In this case, the base class will be replaced with the IEmployed interface. We will also define an Employee class, which is the composite, and a Contractor class. Contractors will be leaf nodes in the hierarchical tree as they are managed but are unable to have subordinates.
The following code shows the elements that are required to obtain the required information:
public interface IEmployed
{
string Name { get; set; }
}
public class Employee : IEmployed, IEnumerable<IEmployed>
{
private List<IEmployed> _subordinates = new List<IEmployed>();
private string _name;
public void AddSubordinate(IEmployed subordinate)
{
_subordinates.Add(subordinate);
}
public void RemoveSubordinate(IEmployed subordinate)
{
_subordinates.Remove(subordinate);
}
public IEmployed GetSubordinate(int index)
{
return _subordinates[index];
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public IEnumerator<IEmployed> GetEnumerator()
{
foreach (IEmployed subordinate in _subordinates)
{
yield return subordinate;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class Contractor : IEmployed
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
21 December 2008