Strategy_Pattern

Strategy Pattern

What’s the Strategy Pattern ?
In the Wiki:

  • defines a family of algorithms,
  • encapsulates each algorithm
  • makes the algorithms interchangeable within that family.

Motivation:

There are common situation when classes differ only in their behavior.For this case is good to isolate the algorithms in separate classes in order to have the ability to select different algorithm at runtime.

Intent

Difine a famliy of algorithms,ecapsulate each one, and make them interchangeable strategy lets the algorithm vary independently from clients that use it.

Example

Strategy -define an interface common to all supported algorithms.Context uses this interface to call algorithm defined by a StrategyPatternDemo.

Context

  • contains a reference to a strategy object.
  • may define an interface that lets strategy accessing its data.

Step 1

Strategy.java

1
2
3
public interface Strategy {
public int doOperation(int num1, int num2);
}

Step 2

OperationAdd.java

1
2
3
4
5
6
public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}

OperationSubstract.java

1
2
3
4
5
6
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}

OperationMultiply.java

1
2
3
4
5
6
public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}

Step 3

Context.java

1
2
3
4
5
6
7
8
9
10
11
public class Context {
private Strategy strategy;

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

public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}

Step 4

StrategyPatternDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

context = new Context(new OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
}

Referance

Adavanteges and Disadvantages