2 Minute Tips: The Strategy Pattern

The “black” of the business world — strategy will never go out of fashion.

By which, I mean the word strategy”.

Such gravitas. Such authority.

As a classically-trained consultant, wrung through the gauntlet of 12 weeks of h??e??a??v??y?? ??d??r??i??n??k??i??n??g?? graduate training, I know all about strategy. I can even use strategy in my code.

Since I have some bandwidth, I’ll bring you up to speed.

Let’s touch base with the 30,000-foot view: the Strategy design pattern allows you to select the behaviour you want dynamically. In practice, this means you can define a family of algorithms, give them a shared interface, and make them interchangeable at runtime.

Sorting Strategies

Let’s not boil the ocean — here’s a command-line app I wrote in 2019 to demo Strategy using a low-hanging fruit: sorting algorithms.

To implement the Strategy pattern, we define our game-changing interface:

protocol SortingAlgorithm {
    func sort(_ numbers: [Int]) -> [Int]
}

Then we create concrete implementations which synergise with said interface:

/// Time:   O(nlogn)
/// Space:  O(logn) 
struct QuickSort: SortingAlgorithm { 
    func sort(_ numbers: [Int]) -> [Int] { ... } 
} 

/// Time:   O(n^2)
/// Space:  O(1)
struct BubbleSort: SortingAlgorithm { 
    func sort(_ numbers: [Int]) -> [Int] { ... }
} 

/// Time:   O(nlogn)
/// Space:  O(n)
struct MergeSort: SortingAlgorithm { 
    func sort(_ numbers: [Int]) -> [Int] { ... }
}

Set a SortingAlgorithm property and run its sort() method to order your array. Modify the strategy variable anytime for a sort-u-ational paradigm shift.

Visit Now