Design Patterns: Composite

Composite pattern is a collection of objects where one of the objects in the collection can branch out. When using this pattern it usually consist of the following elements a component, leaf and composite.

Component:

  • is an abstraction of all components, including the composite ones.
  • declares the interface for the objects in the composition.

Leaf:

  • represents a leaf object in the composition.
  • implements all the Component’s methods.

Composite:

  • represents a composite component.
  • implements methods for manipulating children.
  • implements all Component’s methods

Below are some code snippet taken from the design-patterns repository from my github account, the console application is called Composite and uses a Parent (Composite) and Child (Leaf) objects to represent the use of the pattern.

IMember Interface:

The IMember interface represents the Component and it consist of a method signature called Print(). This interface will be implemented by the Parent and Child class and they will also implement the Print() method for outputing information, but I will explain this later.

using System;

namespace composite
{
public interface IMember
    {
        void Print();
    }
}

(more…)

Shares