<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Animagus on Medium]]></title>
        <description><![CDATA[Stories by Animagus on Medium]]></description>
        <link>https://medium.com/@gauravm8?source=rss-5ced4ac4e57a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*pIcKa1gVdvEOS45E0VkS4g.jpeg</url>
            <title>Stories by Animagus on Medium</title>
            <link>https://medium.com/@gauravm8?source=rss-5ced4ac4e57a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:43:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravm8/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Strategy Design Pattern]]></title>
            <link>https://medium.com/@gauravm8/strategy-design-pattern-1fcd54bca3cf?source=rss-5ced4ac4e57a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fcd54bca3cf</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <dc:creator><![CDATA[Animagus]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 13:01:05 GMT</pubDate>
            <atom:updated>2020-08-31T16:56:43.684Z</atom:updated>
            <content:encoded><![CDATA[<p>Strategy Design Pattern is one of the most useful and widely used design pattern. This pattern gives you a good idea as to why one should use design patterns in production-level code with complex use cases and what benefits they bring to us as developers in maintaining code and making future requirement easier. This pattern is also known as the <strong>Policy Design Pattern.</strong></p><p>Strategy Design pattern is a <strong>Behavioural Pattern</strong> which means it deals with the behaviour of an object. Remember Object Oriented Programming(OOP) is a lot about the <strong>state</strong> and <strong>behaviour</strong> of any object. Let us quickly understand the intent of this pattern.</p><h3>Intent</h3><p>Define a family of algorithms, encapsulate each algorithm, and make them interchangeable dynamically.</p><h4>Let&#39;s explore the Intent of this Pattern</h4><p>If we analyse the intent above it has few keywords worth noting, <strong>algorithm</strong> and <strong>interchangeable</strong>. We can get an idea that this pattern can help us manage something that changes frequently(behaviour) in an object in a better way. So it is something like swapping an algorithm in and out of an object with a different algorithm from a family of algorithms. Also, it has an important inference that <strong>Algorithms can exist independently from the clients that use it</strong>. We can see some benefit here regarding decoupling of algorithm and other code that doesn’t change much.</p><p>After reading the above paragraph, you might be getting a feel that this pattern is promoting <strong>Composition over Inheritance</strong>. Indeed, Strategy Pattern promotes the use of Composition over Inheritance to make algorithms easily changeable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*u-SWKBMPmQkXKNFG.png" /></figure><p>If we look at the above diagram, there are three variations of the Strategy Interface which is essentially our algorithm family. The Context is keeping a reference of a ConcreteStrategy and calling the method doOperation() on the reference to run the algorithm. Clients will create and pass a strategy to the Context.</p><p>Let us have a look at some code.</p><pre>interface FibonacciCalculator { <br>   fun calculateFibonacci(n: Int): Int <br>}</pre><p>Above we have a strategy interface FibonacciCalculator for calculating the Fibonacci Series up to a number n.Here the method calculateFibonacci is analogous to doOperation mentioned above.</p><pre>class RecursiveFibonacciCalculator : FibonacciCalculator {<br><br>    override fun calculateFibonacci(n: Int): Int {<br>        if (n &lt;= 1)<br>            return n;<br>        return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);<br>    }<br>}</pre><pre>class IterativeFibonacciCalculator : FibonacciCalculator {<br><br>    override fun calculateFibonacci(n: Int): Int {<br>        var a = 0<br>        var b = 1<br>        var c = 0<br><br>        for (i in 1 <em>until </em>n) {<br>            c = a + b<br>            a = b<br>            b = c<br>        }<br>        return c<br>    }<br>}</pre><p>Above we have two concrete implementations of FibonacciCalculator in the form of IterativeFibonacciCalculator and RecursiveFibonacciCalculator.These two implementations consist of the family of the algorithms we wish to use and are encapsulated in their separate classes.</p><pre>class FibonacciContext {<br><br>    private lateinit var fibonacciCalculator: FibonacciCalculator<br><br>    fun setFibonacciCalculationStrategy(fibonacciCalculator: FibonacciCalculator) {<br>        this.fibonacciCalculator = fibonacciCalculator<br>    }<br><br>    fun calculateFibonacci(n: Int): Int {<br>        return fibonacciCalculator.calculateFibonacci(n)<br>    }<br>}</pre><p>Here we have the Context class, which uses composition to access the strategy and can execute the strategy. Note that the Context class has no idea regarding which variation of the strategy it is holding.</p><p>Below is the Client code for it :</p><pre>fun main() {<br>    val fibonacciContext = FibonacciContext()<br>        fibonacciContext.setFibonacciCalculationStrategy(IterativeFibonacciCalculator())</pre><pre>    <em>println</em>(fibonacciContext.calculateFibonacci(10))<br><br>    fibonacciContext.setFibonacciCalculationStrategy(RecursiveFibonacciCalculator())<br>    <em>println</em>(fibonacciContext.calculateFibonacci(10))<br>}</pre><p>Output</p><p>55 55</p><p>We got a fair idea on how to implement the strategy design pattern, let us look at some scenarios where we can apply it also its benefits and drawbacks.</p><h3>When to use the Strategy Pattern</h3><ul><li>When we want to keep the Context class code small and manageable we can forward some behaviour to a separate class.</li><li>If you want to have different algorithms based on different environments or situations.</li><li>The algorithm uses data that the Context class should not know about.</li><li>Also if you find many conditionals or If/Switch statements related to behaviour, Strategy Pattern might come handy.</li></ul><h3>Benefits</h3><ul><li><em>Identification, Separation and Reuse of some code.</em></li><li><em>Easy to change strategies/algorithms.</em></li><li><em>Strategies can eliminate conditional statement(if/switch cases are generally considered bad).</em></li></ul><h3>Drawbacks</h3><ul><li><em>Communication overhead between Strategy and Context</em>. Passing data and getting back result from a strategy might be a bit cumbersome.</li><li><em>Increased number of classes and objects</em>. Wrapping head around all the different classes and interfaces in a big project might cause cognitive overload.</li><li><em>Client class should know about all the strategies and which strategy to load inside Context</em>. Client class needs to understand how different strategies work and what are potential trade-offs before it can load the correct strategy.</li></ul><p>Thank You for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fcd54bca3cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>