Definition of the Strategy pattern
In computer programming, the strategy pattern **(also known as the **policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.
Where to use the Factory pattern
When you want the algorithm to vary independently from clients that use it.
UML example
Implementation of the strategy pattern
First, we need to declare an Interface or an Abstract class, here I used both but a single abstract class could have done the job.
package main.strategy; | |
public interface IOperationStrategy { | |
void compute(); | |
} |
package main.strategy; | |
public abstract class AbstractOperationStrategy implements IOperationStrategy { | |
private final int a; | |
private final int b; | |
public AbstractOperationStrategy(int a, int b){ | |
this.a = a; | |
this.b = b; | |
} | |
public int getA() { | |
return a; | |
} | |
public int getB() { | |
return b; | |
} | |
} |
what i want to achieve is that depending of the context my code will behave differently so let’s implement some strategy.
For the purpose of this tutorial, i created 2 strategies : PlusOperationStrategy and MinusOperationStrategy, both extending my abstract class.
package main.strategy; | |
public final class PlusOperationStrategy extends AbstractOperationStrategy { | |
public PlusOperationStrategy(int a, int b){ | |
super(a, b); | |
} | |
@Override | |
public void compute() { | |
System.out.println(getA() + getB()); | |
} | |
} |
package main.strategy; | |
public final class MinusOperationStrategy extends AbstractOperationStrategy{ | |
public MinusOperationStrategy(int a, int b){ | |
super(a, b); | |
} | |
@Override | |
public void compute() { | |
System.out.println(getA() - getB()); | |
} | |
} |
With them being of the same supertype by inheritance, I can substitute them in the function of the needed behavior.
So now, if I want to use my strategies, and more precisely the compute method implemented in it, I need a context.
package main.strategy; | |
public class CalculatorContext { | |
private IOperationStrategy strategy; | |
public CalculatorContext(IOperationStrategy strategy){ | |
this.strategy = strategy; | |
} | |
public void compute(){ | |
this.strategy.compute(); | |
} | |
} |
So based on the strategy passed as a parameter the context will use the compute method it.
So now, let’s see how it work
package main.strategy; | |
public class StrategyMain { | |
public static void main(String[] args) { | |
CalculatorContext ctx = new CalculatorContext(new PlusOperationStrategy(2, 3)); | |
ctx.compute(); | |
ctx = new CalculatorContext(new MinusOperationStrategy(2, 3)); | |
ctx.compute(); | |
} | |
} |
The above snippet will return this result
5
-1
Thanks for your reading time, the code used in this tutorial is findable in this Github repository.
Top comments (0)