Composite

You have to make a program for a car maker company.
Your program has to calculate the factory price of each car.
You have the prices of the car parts.
You have the list of car parts of each car.
To test your program the company gives you the factory price of the XYZ car.

You made your program and launch it with the XYZ car.
Of course, the price that you program found is different :)

After some hours to find a bug in your code... you understand.
In the list of prices there are some bundles of car parts.
These bundles are sometimes less expensive than the sum of car parts prices.
Some car models use these bundles... and the XYZ model too.

You understood so you modify your code to fix the problem.
  1. A "car" is not a parts list but a tree structure of components.
  2. A component can be :
    • a car part
    • a bundle (= composite) composed by other components
  3. A component is able to give his price.
    • Car part
      • you already know the price
    • Bundle (= composite)
      • maybe you already know the price
      • else the price is the sum of his components prices
THIS IS THE COMPOSITE DESIGN PATTERN !!!


When you will be in the same situation =
A group (tree structure) of different objects have to be treated in the same way.

Don't make "if/else" block to manage each case, just apply composite.

You will declare the common treatment in a X interface ("Priceable" in example).
Your classes will implement the X interface.
You will make a Composite class (implementing X too) to group your X objects.