Skip to content

Instantly share code, notes, and snippets.

@slmanju
Created January 25, 2018 12:01
Show Gist options
  • Save slmanju/cae7066286fdd8ac60cb5540910b4e46 to your computer and use it in GitHub Desktop.
Save slmanju/cae7066286fdd8ac60cb5540910b4e46 to your computer and use it in GitHub Desktop.
Strategy design pattern with Java
public interface Algorithm {
void execute();
}
public class AlgorithmA implements Algorithm {
@Override
public void execute() {
System.out.println("doing great in A");
}
}
public class AlgorithmB implements Algorithm {
@Override
public void execute() {
System.out.println("B is doing great");
}
}
public class StrategyContext {
private Algorithm algorithm;
public StrategyContext(Algorithm algorithm) {
this.algorithm = algorithm;
}
public void doIt() {
this.algorithm.execute();
}
public void setAlgorithm(Algorithm algorithm) {
this.algorithm = algorithm;
}
}
public class StrategyDemo {
public static void main(String[] args) {
Algorithm algorithmA = new AlgorithmA();
Algorithm algorithmB = new AlgorithmB();
StrategyContext strategyContext = new StrategyContext(algorithmA);
strategyContext.doIt();
strategyContext.setAlgorithm(algorithmB);
strategyContext.doIt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment