The Composite Pattern

The Composite Pattern creates a mechanism for trading individual objects and compositions of objects in a uniform manner.

What the heck is this definition!?? This is why programming sounds crazy for some. It is sometimes difficult to define programming concepts simply and concisely.

What this composite pattern seeks to do is to handle objects that are composed of other “similar” objects. It is actually very simple. Simply think of a tree of objects with the same behavior. Let’s say we want to know how much each employee, manager, and branch of a bank manages.

public class Employee {  // Leaf
   public double calculatePortfolio() { ... }
}

public class Manager {  // Composite
   private List<Employee> employees;
   private List<Managers> managers; // a manager can manage other managers
   public double calculatePortfolio() { 
     return employees
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
     + managers
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
   }
}

public class Branch { // Other composite or component
  private List<Manager> managers;
  public double calculatePortfolio() {
    return managers
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
  }
}

By calling the calculatePortfolio method, we are able to get the amount of money managed at each level of the tree.

Author: Toujon Lyfoung

This paragraph is supposed to be the place where I put my credentials and achievements. In my opinion, degrees and jobs do not tell much about a person. If you want to know me, read my posts! Blogging has been fun. I do not pretend to do much. I am simply processing, tracking and sharing my reflection. Comments are definitely welcomed to help me continue in my learning.

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