How to implement Strategy Design Pattern in C#

Strategy Design Pattern

In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code


In this blog post I will discuss about one of the most used design pattern "Strategy design pattern"

By the end of this blog post you will be able to understand

  • What is Strategy design pattern?
  • How to implement Strategy design pattern in C# with real world example
  • Where to use Strategy design pattern? 

What is Strategy design pattern?

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Strategy Design Pattern

Problem

Client wants to decide at run-time what serialization it should use to serialize a type. Many different serialization algorithms are already available.
Strategy Design Pattern

Solution

Encapsulate the different serialization algorithms using the Strategy pattern!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{

    public interface ISerializer
    {
        void Serialize();
    }
    public class XmlSerializer : ISerializer
    {
        public void Serialize()
        {
            Console.WriteLine("Xml serilizer Invoked");
        }
    }
    public class JsonSerializer : ISerializer
    {
        public void Serialize()
        {
            Console.WriteLine("Json serializer Invoked");
        }
    }
    public class Context
    {
        private ISerializer _serializer;
        public Context(ISerializer serializer)
        {
            this._serializer = serializer;
        }
        public void Serialize()
        {
            _serializer.Serialize();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Context ctx = new Context(new XmlSerializer());
            ctx.Serialize();
        }
    }
}

Patterns You’re Already Using in the .NET Framework.

.NET Framework List<T> and ArrayList Sort method uses Strategy design pattern in the Sort method.

Sort<T>(T[], IComparer<T>)

Refrences

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم