Software Design Pattern By Example: Strategy
Explain Strategy Design Pattern in an easy-to-understand example
A repost of my past article on Medium.
(I know the majority of this blog’s readers are testers or automation/DevOps engineers. This one is about software design.)
Table of Contents:
· The Problem: GCD
· Preparation
∘ Implement individual algorithms
· Sub-optimal Design
· Strategy Pattern
· Apply Strategy pattern again
· Exercise
∘ A quick introduction to Object-Oriented in C++
The Problem: GCD
In mathematics, the greatest common divisor (GCD, also called the greatest common factor) of two or more integers (not all zero), is the largest positive integer that divides each of the integers. For example, the gcd of 8 and 12 is 4, and the gcd of 6, 8, 12 is 2.
In this exercise, you implement at least two algorithms to solve the GCD of two integers x
and y
. The program will decide the use of algorithms dynamically based on the multiple of x, y
. For example, If x * y > 100000
using algorithm A
, otherwise B
. The decision logic does not matter, as long as the program demonstrates it can ‘choose’ a different algorithm.
Preparation
As always, start simple and make small progress.
Implement 2+ GCD algorithms.
It is OK to start with a procedural style (i.e. non-OO design).Encapsulate implementations in classes
Wrap your implementations into several meaningful classes. See below for a super-short introduction of OO in C++Optimize the design
The goal of this exercise is to ensure your design is flexible, you may do a self-assessment by asking yourself the following questions:
— how much will it affect my program if the decision logic changes?
— how easy is it to add another algorithm?
Implement individual algorithms
Keep reading with a 7-day free trial
Subscribe to The Agile Way to keep reading this post and get 7 days of free access to the full post archives.