Software Design Pattern By Example: Strategy

Explain Strategy Design Pattern in an easy-to-understand example

Zhimin Zhan
4 min readNov 26, 2021

--

(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, 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.

  1. Implement 2+ GCD algorithms.
    It is OK to start with procedural style (i.e. non-OO design).
  2. Encapsulate implementations in classes
    Wrap your implementations…

--

--

Zhimin Zhan

Test automation & CT coach, author, speaker and award-winning software developer. Help teams succeed with Agile/DevOps by implementing real Continuous Testing.