다음 Java 로직을 C++로 구현해 보자.
[Java]
// strategy.java
public interface Strategy {
public int doOperation(int num1, int num2);
}
// OperationAdd.java
public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
// OperationSubstract.java
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
// OperationMultiply.java
public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
// Context.java
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
// StrategyPatternDemo.java
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
}
[C++]
#include <iostream>
using namespace std;
class Strategy{
public:
virtual int doOperation (int num1, int num2) = 0;
};
class OperationAdd : public Strategy{
public:
int doOperation(int num1, int num2) override{
return num1 + num2;
}
};
class OperationSubstract : public Strategy{
public:
int doOperation(int num1, int num2) override{
return num1 - num2;
}
};
class OperationMultiply : public Strategy{
public:
int doOperation(int num1, int num2) override{
return num1 * num2;
}
};
class Context {
private:
Strategy *strategy;
public:
Context(Strategy *strategy){ this->strategy = strategy; }
int executeStrategy(int num1, int num2) { return strategy->doOperation(num1, num2); }
};
int main(){
Context *context = new Context(new OperationAdd);
cout << "10 + 5 = " << context->executeStrategy(10, 5) << endl;
context = new Context(new OperationSubstract());
cout << "10 - 5 = " << context->executeStrategy(10, 5) << endl;
context = new Context(new OperationMultiply());
cout << "10 * 5 = " << context->executeStrategy(10, 5) << endl;
}
핵심 포인트!
1. private에 Strategy 클래스의 객체를 생성할 수 있다.
2. 생성자의 매개변수로 객체를 생성할 수 있다.
class Context {
private:
Strategy *strategy;
public:
Context(Strategy *strategy){ this->strategy = strategy; }
int executeStrategy(int num1, int num2) { return strategy->doOperation(num1, num2); }
};
'C | C++ > Modern C++' 카테고리의 다른 글
Design Pattern II_Strategy Pattern, Observer Pattern, Adapter Pattern (0) | 2022.11.13 |
---|---|
Design Pattern I_Singleton, Factory method, bridge pattern (0) | 2022.11.10 |
[TCPL]_ 1부(prev) Tip 정리. (0) | 2022.11.01 |
[Effective Modern C++ item 1]: template 형식 연역 규칙을 숙지하라! (0) | 2022.10.28 |
☆Prev. C++, Modern C++의 변화 (2) | 2022.10.28 |