Created
January 25, 2018 12:01
-
-
Save slmanju/cae7066286fdd8ac60cb5540910b4e46 to your computer and use it in GitHub Desktop.
Strategy design pattern with Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Algorithm { | |
void execute(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AlgorithmA implements Algorithm { | |
@Override | |
public void execute() { | |
System.out.println("doing great in A"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AlgorithmB implements Algorithm { | |
@Override | |
public void execute() { | |
System.out.println("B is doing great"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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