#
Strategy
This tutorial explains to you the design pattern named Strategy (which is a Structural Pattern).
#
Strategy Pattern - theory
Strategy
Design Pattern in Java is used when we want to adopt a strategy function of context.
This pattern makes the Java application easier to extend and incorporate new behaviors.
The Strategy Pattern is also known as Policy
.
Take a look at the following UML diagram representing the Strategy design pattern (for my example):
#
Strategy Pattern - example
Here is an example of using the Strategy Design Pattern in Java:
package strategy.java.pattern.example;
public interface ToDo {
public void enjoy();
}
package strategy.java.pattern.example;
public class IsWinter implements ToDo {
@Override
public void enjoy() {
System.out.println("You GO SKIING.");
System.out.println("You BUILD a SNOWMAN.");
}
}
package strategy.java.pattern.example;
public class IsSummer implements ToDo {
@Override
public void enjoy() {
System.out.println("You GO SWIMMING.");
System.out.println("You PLAY SOCCER.");
}
}
package strategy.java.pattern.example;
public class Context {
private ToDo toDo;
public Context(ToDo toDo){
this.toDo = toDo;
}
public void contextEnjoy(){
toDo.enjoy();
}
}
package strategy.java.pattern.example;
public class StrategyJavaPatternExample {
public static void main(String[] args) {
ToDo winter = new IsWinter();
Context context1 = new Context(winter);
context1.contextEnjoy();
System.out.println("");
ToDo summer = new IsSummer();
Context context2 = new Context(summer);
context2.contextEnjoy();
}
}
When you run this example you will receive the following result: