C# Composite Pattern

C# Composite Pattern tutorial

Advertisements

Link to source code for this post

Composite pattern is used to create a tree structure, where every item of the structure implements the same interface. Therefore methods declared in interface can performed on every item in the structure. This pattern classifies each element in the tree as a composite or a leaf. A composite means that there can be other elements below it, whereas a leaf cannot have any elements below it.

To demonstrate the implementation of this pattern I’ll use an example of inventory where player can have Items( leafs ) and Backpack ( composite ). Player will be able to loop through all items in inventory and return the name of the items.

 

UML diagram

l5

 

First thing to create is the Component interface that will be inherited by all items in the structure.

public interface IInventory
{
  string Name { get; set; }
  void PrintName();
}

It acts as the base class for all the objects within the hierarchy. I’m creating name property for all items. you can find more about properties on my recent post about it.

Next thing is the implementation of the interface in Backpack Class that will be used to store Items or other Backpacks. To do this You need method for adding and removing items. Objects will be stored in generic List.


public class Backpack : IInventory, IEnumerable<IInventory>
{
  private List<IInventory> _subordinates = new List<IInventory>();

  public string Name { get; set; }

  public void AddSubordinate(IInventory subordinate)
  {
    _subordinates.Add(subordinate);
  }

  public void RemoveSubordinate(IInventory subordinate)
  {
    _subordinates.Remove(subordinate);
  }

  public IInventory GetSubordinate(int index)
  {
    return _subordinates[index];
  }

  public void PrintName()
  {
    Console.WriteLine(Name);
  }
  public IEnumerator<IInventory> GetEnumerator()
  {
    foreach (IInventory subordinate in _subordinates)
    {
      yield return subordinate;
    }
  }

  IEnumerator IEnumerable.GetEnumerator()
  {
    return GetEnumerator();
  }
}

Next thing is  to create an object Class, this class will be used to represent single item in inventory.

 public class Item : IInventory
{
  public string Name { get; set; }

  public void PrintName()
  {
    Console.WriteLine(Name);
  }
}

Last thing to do is the Client site that will create the structure based on the created Interface and Classes.

 class Program
{
  static void Main(string[] args)
  {
    Backpack inventory = new Backpack { Name = "Inventory" };
    Backpack backpack = new Backpack { Name = "Backpack" };

    inventory.AddSubordinate(backpack);
    inventory.AddSubordinate(new Item { Name = "Sword"});
    inventory.AddSubordinate(new Item { Name = "Armor" });

    backpack.AddSubordinate(new Item { Name = "Shield" });

    Console.WriteLine("List of items in inventory");

      foreach (IInventory element in inventory)
      {
         element.PrintName();
      }
    Console.ReadKey();
   }
 }

In this example Backpack class is used to create rot object for the tree. Where new backpack and few new items are added. Thanks to implementation of IEnumerable interface we can loop through items in the backpack class.

To conclude, Composite pattern compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. I hope you find this tutorial useful. If you have any questions feel free to ask in comments. In next part I’ll cover yet another design pattern. Stay Awesome!

Author: indiedevart

Indie Games Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s