Member-only story

Software Design Pattern By Example: Strategy

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

Zhimin Zhan
4 min readNov 26, 2021

This article is also on Substack.

(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 into several meaningful classes. See below for a super-short introduction of OO in C++
  3. Optimize the design
    The goal of this exercise is to ensure your design is flexible, which you may do self-assessment by asking yourself the following questions:
    — how much it will affect my program if the decision logic changes?
    — how easy is it to add another algorithm?

Implement individual algorithms

The actual implementation of algorithms is not the focus of this exercise, feel free to copy the solutions from the Internet. I recommend the following algorithms:

  • Classic GCD Algorithm
    Get a list of divisors of x and look for the first one from the highest that is also a divisor of y.
    Example code on GeeksForGeeks: get all prime factors
  • Euclidean GCD Algorithm
    Using recursive calls, the…

--

--

Zhimin Zhan
Zhimin Zhan

Written by Zhimin Zhan

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

No responses yet

Write a response