반응형
전략 패턴 알고리즘은 런타임에 변경할 수 있습니다.
전략 패턴은 행동 패턴입니다.
전략 패턴에서 알고리즘을 실행하려면 다양한 알고리즘과 컨텍스트 객체를 생성합니다.
전략 객체는 컨텍스트 객체에 대한 알고리즘을 변경합니다.
예제
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
반응형
'프로그래밍 > 자바 디자인 패턴' 카테고리의 다른 글
자바 디자인 패턴 튜토리얼 - 행동 디자인 패턴 - 반복자 패턴 (0) | 2021.04.18 |
---|---|
자바 디자인 패턴 튜토리얼 - 행동 디자인 패턴 - 옵저버 패턴 (0) | 2021.04.18 |
자바 디자인 패턴 튜토리얼 - 행동 디자인 패턴 - 자바 인터프린터 패턴 (0) | 2021.04.18 |
자바 디자인 패턴 튜토리얼 - 행동 디자인 패턴 - 상태 패턴 (0) | 2021.04.18 |
자바 디자인 패턴 튜토리얼 - 행동 디자인 패턴 - 자바 NULL 오브젝트 패턴 (0) | 2021.04.18 |