프로그래밍/자바 디자인 패턴
자바 디자인 패턴 튜토리얼 - 행동 디자인 패턴 - 전략 패턴
Ericlee
2021. 4. 18. 02:22
반응형
전략 패턴 알고리즘은 런타임에 변경할 수 있습니다.
전략 패턴은 행동 패턴입니다.
전략 패턴에서 알고리즘을 실행하려면 다양한 알고리즘과 컨텍스트 객체를 생성합니다.
전략 객체는 컨텍스트 객체에 대한 알고리즘을 변경합니다.
예제
interface MathAlgorithm {
public int calculate(int num1, int num2);
}
class MathAdd implements MathAlgorithm{
@Override
public int calculate(int num1, int num2) {
return num1 + num2;
}
}
class MathSubstract implements MathAlgorithm{
@Override
public int calculate(int num1, int num2) {
return num1 - num2;
}
}
class MathMultiply implements MathAlgorithm{
@Override
public int calculate(int num1, int num2) {
return num1 * num2;
}
}
class MathContext {
private MathAlgorithm algorithm;
public MathContext(MathAlgorithm strategy){
this.algorithm = strategy;
}
public int execute(int num1, int num2){
return algorithm.calculate(num1, num2);
}
}
public class Main {
public static void main(String[] args) {
MathContext context = new MathContext(new MathAdd());
System.out.println("10 + 5 = " + context.execute(10, 5));
context = new MathContext(new MathSubstract());
System.out.println("10 - 5 = " + context.execute(10, 5));
context = new MathContext(new MathMultiply());
System.out.println("10 * 5 = " + context.execute(10, 5));
}
}
위의 코드는 다음 결과를 출력합니다
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
반응형