2 Minute Tips: The Strategy Pattern
<p>The “black” of the business world — strategy will never go out of fashion.</p>
<p>By which, I mean the word <em>“</em>strategy”.</p>
<p>Such gravitas. Such authority.</p>
<p>As a classically-trained consultant, wrung through the gauntlet of 12 weeks of <code>h̶e̶a̶v̶y̶ ̶d̶r̶i̶n̶k̶i̶n̶g̶</code> graduate training, I know all about strategy. <strong>I can even use strategy in my code</strong>.</p>
<p>Since I have some bandwidth, I’ll bring you up to speed.</p>
<p>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.</p>
<h2>Sorting Strategies</h2>
<p>Let’s not boil the ocean — <a href="https://github.com/jacobsapps/swift-design-patterns/tree/master/Behavioral/Strategy" rel="noopener ugc nofollow" target="_blank">here’s a command-line app</a> I wrote in 2019 to demo Strategy using a low-hanging fruit: sorting algorithms.</p>
<p>To implement the Strategy pattern, we define our game-changing interface:</p>
<pre>
protocol SortingAlgorithm {
func sort(_ numbers: [Int]) -> [Int]
}</pre>
<p>Then we create concrete implementations which synergise with said interface:</p>
<pre>
/// 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] { ... }
}</pre>
<p>Set a <code>SortingAlgorithm</code> property and run its <code>sort()</code> method to order your array. Modify the <code>strategy</code> variable anytime for a sort-u-ational paradigm shift.</p>
<p><a href="https://medium.com/@jacobmartinbartlett/2-minute-tips-the-strategy-pattern-93a9fb997513">Visit Now</a></p>