Strategy - Design Pattern

Strategy - Design Pattern

Software Architecture Simplified

Jul 7, 2022·

2 min read

Objective 🎯

Allow an algorithm to be changed at run time based on pre-defined conditions

Type ✅

✔️Behavioral: Describes how objects interact/communicate between themselves.

❌Creational: Describes how to instantiate an object without large and complex.

❌Structural: Describes how objects/classes are composed to form larger structures.

UML 📐

image.png

Participants 🔗

• Strategy:

  • Declares an interface common to all supported algorithms

• ConcreteStrategy:

  • Implements the algorithm respecting the Strategy interface

• Context:

  • Maintains a reference to a concrete Strategy

Sample Code 🎮

Structural Example 🏛️

image.png

public static class StrategyStructural
    {
        public static void Execute()
        {
            Context lContext = new Context(new ConcreteStrategyA());
            lContext.ContextOperation();

            lContext = new Context(new ConcreteStrategyB());
            lContext.ContextOperation();
        }

        public abstract class Strategy
        {
            public abstract void StrategyOperation();
        }

        public class ConcreteStrategyA : Strategy
        {
            public override void StrategyOperation()
            {
                Console.WriteLine("Executing Operation Using Strategy A");
            }
        }

        public class ConcreteStrategyB : Strategy
        {
            public override void StrategyOperation()
            {
                Console.WriteLine("Executing Operation Using Strategy B");
            }
        }

        public class Context
        {
            private Strategy _Strategy;

            public Context(Strategy prStrategy)
            {
                this._Strategy = prStrategy;
            }

            public void ContextOperation()
            {
                _Strategy.StrategyOperation();
            }
        }
    }

Output

image.png

Real-world Example 🔥

image.png

public static class StrategyPractical
    {
        public static void Execute()
        {
            SortedListContext lSortedListContext = new SortedListContext();
            lSortedListContext.AddItem("D");
            lSortedListContext.AddItem("B");
            lSortedListContext.AddItem("A");
            lSortedListContext.AddItem("C");
            lSortedListContext.AddItem("E");
            lSortedListContext.AddItem("G");
            lSortedListContext.AddItem("F");

            lSortedListContext.SetSortStrategy(new Ascending());
            lSortedListContext.Sort();

            lSortedListContext.SetSortStrategy(new Descending());
            lSortedListContext.Sort();

            lSortedListContext.SetSortStrategy(new Random());
            lSortedListContext.Sort();
        }
    }

    public abstract class SortStrategy
    {
        public abstract List<string> Sort(List<string> prItems);
    }

    public class Ascending : SortStrategy
    {
        public override List<string> Sort(List<string> prItems)
        {
            prItems = prItems.OrderBy(x => x).ToList();
            Console.WriteLine("Ascending Strategy - Result: " + String.Join(", ", prItems));
            return prItems;
        }
    }

    public class Descending : SortStrategy
    {
        public override List<string> Sort(List<string> prItems)
        {
            prItems = prItems.OrderByDescending(x => x).ToList();
            Console.WriteLine("Descending Strategy - Result: " + String.Join(", ", prItems));
            return prItems;
        }
    }

    public class Random : SortStrategy
    {
        public override List<string> Sort(List<string> prItems)
        {
            prItems = prItems.OrderBy(x => System.Guid.NewGuid().ToString()).ToList();
            Console.WriteLine("Random Strategy - Result: " + String.Join(", ", prItems));
            return prItems;
        }
    }

    public class SortedListContext
    {
        private List<string> _Items = new List<string>();
        private SortStrategy _SortStrategy;

        public void SetSortStrategy(SortStrategy prSortStrategy)
        {
            this._SortStrategy = prSortStrategy;
        }

        public void AddItem(string prItem)
        {
            _Items.Add(prItem);
        }

        public void Sort()
        {
            _SortStrategy.Sort(_Items);
        }
    }

Output

image.png

Source Code 🎲

github.com/VictorLins/DesignPatterns

Did you find this article valuable?

Support Victor Lins by becoming a sponsor. Any amount is appreciated!