Sunday, 9 June 2013

Composite pattern in action

I recently found myself frequently using composite pattern to solve some software design problems ranging from numerical calculations to business rules validation and complex form print operations. The more I use this pattern the more I like it. These days my favourite pattern is composite pattern.
Composite pattern helps solving a computation problem by splitting the problem into sub tasks, Each sub task can take some parameter and return a computed value which can be passed to other sub tasks.
For example calculating a polynomial function f (x)=  ( (x^3 + 1/x ) ^4 ) –9 in java may look a bit weird. However once the problem is defined as sub problems, solution is on the horizon.
I will start off first declaring an interface which takes the variable x as the parameter.

Second step is trying some simple polynomials, for example f (x)=x+1, f (x)=4.
In the first example function is sum of two functions, namely identity and constant, so I can try defining an identity and constant function and summation function which is sum of all given functions.
Identity function will return whatever value is passed to itself and looks like below.

On the other hand, a constant function returns a predefined value regardless of the parameter being passed.


With similar approach an add function can be defined as below.

It is interesting to see that add function is made of functions passed as parameters. Add function eventually executes each function passed and then generates a sum of values as its value.

That approach enables splitting problem and solve each sub problem individually. When all sub solutions are combined, a powerful composite whole solution is made of. A composite structure enables solving complex problems meanwhile building strong solution hierarchy and encapsulation. Following same pattern I have created PowerFunction and MultiplyFunction and created a test case to see my function composite in action.


After applying same methology, I have created MultiplyFunction,DivFunction and MinusFunction to complete my class hierarchy.

All completed functions can be found on github

No comments:

Post a Comment