Skip to content

Commit

Permalink
Composite pattern details added #53 (#56)
Browse files Browse the repository at this point in the history
* Initiate design patterns documentations in Markdown format #53

* Added prototype pattern details and created temp markdown files #53

* Added composite pattern details #53
hacktober fest 2023 accepted
  • Loading branch information
manas11 authored Oct 4, 2023
1 parent ba29d51 commit 6b57c9e
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions DesignPatterns/composite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Composite

Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects.



Problem
Using the Composite pattern makes sense only when the core model of your app can be represented as a tree.

For example, imagine that you have two types of objects: Products and Boxes. A Box can contain several Products as well as a number of smaller Boxes. These little Boxes can also hold some Products or even smaller Boxes, and so on.

Say you decide to create an ordering system that uses these classes. Orders could contain simple products without any wrapping, as well as boxes stuffed with products...and other boxes. How would you determine the total price of such an order?


You could try the direct approach: unwrap all the boxes, go over all the products and then calculate the total. That would be doable in the real world; but in a program, it’s not as simple as running a loop. You have to know the classes of Products and Boxes you’re going through, the nesting level of the boxes and other nasty details beforehand. All of this makes the direct approach either too awkward or even impossible.

Solution
The Composite pattern suggests that you work with Products and Boxes through a common interface which declares a method for calculating the total price.

How would this method work? For a product, it’d simply return the product’s price. For a box, it’d go over each item the box contains, ask its price and then return a total for this box. If one of these items were a smaller box, that box would also start going over its contents and so on, until the prices of all inner components were calculated. A box could even add some extra cost to the final price, such as packaging cost.



The greatest benefit of this approach is that you don’t need to care about the concrete classes of objects that compose the tree. You don’t need to know whether an object is a simple product or a sophisticated box. You can treat them all the same via the common interface. When you call a method, the objects themselves pass the request down the tree.

0 comments on commit 6b57c9e

Please sign in to comment.