Facebook Pixel

Exercise: Strategy

This exercise puts the Strategy pattern into code.

Scenario

A Calculator collects integers and applies a reduction when asked. The active reduction algorithm can be changed at any time. Three algorithms are supported: sum, max, and min. The default before any strategy command is sum. If no numbers have been pushed, any strategy returns 0.

Commands

CommandBehaviorOutput
["push", n]Append the integer n to the list(none)
["strategy", name]Set the active strategy to "sum", "max", or "min"(none)
["run"]Apply the active strategy over all pushed numbersthe integer result as a string
Example
Input
7
run
push 5
push 3
push 8
run
strategy max
run
Output
0
16
8
Explanation
The first `run` fires before any numbers are pushed; with an empty list the default sum strategy returns 0. After pushing 5, 3, and 8, the second `run` applies the sum strategy and returns 16. Switching to `max` and running again returns 8, the largest of the three values. Note that `push` and `strategy` produce no output; only `run` prints a line.

Your task

Create SumStrategy, MaxStrategy, and MinStrategy (each implements the ReductionStrategy base) so the commands produce the output described above. The starter keeps the ReductionStrategy base, the Calculator, and the registry, and marks where to add the three strategy classes with a TODO comment listing each class's method signature and behavior.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro