Exploring Design Patterns — Composite Pattern (Basic Arithmetic Expression)

Koushikr
2 min readApr 3, 2022

Hey guys,

We’ll be exploring composite pattern in this article. If you haven’t read my article about decorator pattern, please look here — https://koushikragavendran.medium.com/exploring-design-patterns-decorator-pattern-ca3aafc50637. Let us not waste time and start exploring.

An example of nested arithmetic expression

Consider a simple expression 5 + 3. To calculate the value of the expression, a simple “Expression” java class can be used that has information of the left operand and right operand and operation to perform as shown below snippet.

A new expression object is created with 5 as a left operand and 3 as a right operand, and ADD operation. When the method “getValue” is called the sum of 5 and 3, 8 is returned. The above design works all good only if the expression has two operands and one operator. But, expression can have more than two operands and more than one operator.

Consider 8 * 3 / 4 + 2 as the expression. Applying the “BODMAS” rule, 3 is divided by 4 initially, multiplied by 8 and added to 2. The result of the expression is 8. If we look closely, the expression itself has expression. In such cases, “COMPOSITE PATTERN” can help us. Please have a look at the code snippet below.

The Operation expression has left and right expressions. By calling the “getValue” method of the expression, the result is calculated by calculating the values of sub-expressions. The above design can be modified to based on the requirement as well.

Hope this help!

Reference:

  1. Elisabeth Freeman, Eric Freeman, Bert Bates, and Kathy Sierra. 2004. Head First Design Patterns. O’ Reilly & Associates, Inc.

--

--