sabato 27 aprile 2019

Design Patterns: Strategy Pattern

In the latest years design pattern programming seems a must if you want to work in a development team, especially java and C#. What I think is that a good programmer only need common sense.

This is very simplified explanation of strategy pattern:
Strategy pattern is when you want use different strategy or algorithms to process data. For example you want to use different types of sort: quick sort, bubble sort,etc, in this case the strategy is the sort algorithm. You have to create an abstract class Strategy with a method to apply the strategy, then you have to implement the strategies classes inherit from Strategy class that overload the same method with their strategy.
At the end you have to create a context class that has a private Strategy member, in the constructor you pass the strategy class (Ex: quick sort) and a method to implement the strategy that will call the strategy.strategy method.

public abstract class Strategy
{
public abstract double applyAlgorithm(int a,int b),
}

public class FirstAlghorithm extends Strategy
{
@Override
         public double ApplyAlgorithm(int a,int b)
         {
// do calculation
}
}

public class SecondAlghorithm extends Strategy
{
@Override
         public double ApplyAlgorithm(int a,int b)
         {
// do calculation
}
}

public class Context
{
         private Strategy strategy,
   
         public Context(Strategy strategy)
         {
                this.strategy = strategy;
         } 

         public double applyAlgorithm(int a,int b)
         {
return strategy.ApplyAlgorithm(a,b);
}
}

Usage:

Context ctx = new Context( new FirstStrategy());

double result = ctx.ApplyAlgorithm( 4, 2);


In case of sorting strategies the previous example  become:

public abstract class StrategySort
{
public abstract void Sort(int[] array),
}

public class MergeSort extends StrategySort
{
@Override
        public void Sort(int[] array)         
        {
// do merge sort in array
}
}

public class QuickSort extends StrategySort
{
@Override
        public void Sort(int[] array)         
        {
// do quicksort in array
}
}

public class Context
{
         private StrategySort strategy,
   
         public Context(StrategySort strategy)
         {
                this.strategy = strategy;
         } 

        public void Sort(int[] array)         
        {
strategy.Sort(array);
}
}

Usage:

Context ctx = new Context( new QuickSort());

double result = ctx.Sort(array);





Nessun commento:

Posta un commento