Strategy Design Pattern

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😊

Post a Comment (0)
Previous Post Next Post