2 Minute Tips: The Strategy Pattern

<p>The &ldquo;black&rdquo; of the business world &mdash; strategy will never go out of fashion.</p> <p>By which, I mean the word&nbsp;<em>&ldquo;</em>strategy&rdquo;.</p> <p>Such gravitas. Such authority.</p> <p>As a classically-trained consultant, wrung through the gauntlet of 12 weeks of&nbsp;<code>h̶e̶a̶v̶y̶ ̶d̶r̶i̶n̶k̶i̶n̶g̶</code>&nbsp;graduate training, I know all about strategy.&nbsp;<strong>I can even use strategy in my code</strong>.</p> <p>Since I have some bandwidth, I&rsquo;ll bring you up to speed.</p> <p>Let&rsquo;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&rsquo;s not boil the ocean &mdash;&nbsp;<a href="https://github.com/jacobsapps/swift-design-patterns/tree/master/Behavioral/Strategy" rel="noopener ugc nofollow" target="_blank">here&rsquo;s a command-line app</a>&nbsp;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]) -&gt; [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]) -&gt; [Int] { ... } } /// Time: O(n^2) /// Space: O(1) struct BubbleSort: SortingAlgorithm { func sort(_ numbers: [Int]) -&gt; [Int] { ... } } /// Time: O(nlogn) /// Space: O(n) struct MergeSort: SortingAlgorithm { func sort(_ numbers: [Int]) -&gt; [Int] { ... } }</pre> <p>Set a&nbsp;<code>SortingAlgorithm</code>&nbsp;property and run its&nbsp;<code>sort()</code>&nbsp;method to order your array. Modify the&nbsp;<code>strategy</code>&nbsp;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>