dimanche 19 mai 2019

The Strategy design pattern vs simple Interface abstraction?

AFAIK , the strategy design pattern is pretty simple :

Interface :

public interface IStrategy
    {
        object DoAlgorithm(object data);
    }

Implementing classes :

lass ConcreteStrategyA : IStrategy
    {
        public object DoAlgorithm(object data)
        {
            var list = data as List<string>;
            list.Sort();
            return list;
        }
    }


 class ConcreteStrategyB : IStrategy
    {
        public object DoAlgorithm(object data)
        {
            var list = data as List<string>;
            list.Sort();
            list.Reverse();

            return list;
        }
    }

A context class which gets IStrategy in ctor :

class Context
    {

        private IStrategy _strategy;


        public Context(IStrategy strategy)
        {
            this._strategy = strategy;
        }

        public void SetStrategy(IStrategy strategy)
        {
            this._strategy = strategy;
        }

        public void DoSomeBusinessLogic()
        {
            ////
        }
    }

And of course , the Main method:

var context = new Context();
Console.WriteLine("Client: Strategy is set to normal sorting.");
context.SetStrategy(new ConcreteStrategyA());
context.DoSomeBusinessLogic();

Question:

OK , But how does it make any difference as opposed to :

Istrategy context = new ConcreteStrategyA (); //or ConcreteStrategyB
Console.WriteLine("Client: Strategy is set to normal sorting.");
context.DoSomeBusinessLogic();

Am I missing something ? why not just using interfaces?

Aucun commentaire:

Enregistrer un commentaire