-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.cc
More file actions
52 lines (42 loc) · 1.2 KB
/
Copy pathcalculator.cc
File metadata and controls
52 lines (42 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright 2024 JOK Inc. All Rights Reserved.
// Author: easytojoin@163.com (jok)
#include <iostream>
class IStrategy {
public:
virtual int execute(int, int) const = 0;
};
class AddStrategy : public IStrategy {
public:
int execute(int a, int b) const override { return a + b; }
};
class SubtractStrategy : public IStrategy {
public:
int execute(int a, int b) const override { return a - b; }
};
class MultiplyStrategy : public IStrategy {
public:
int execute(int a, int b) const override { return a * b; }
};
class Context {
public:
explicit Context(const IStrategy* strategy) : strategy_(strategy) {}
void setStrategy(const IStrategy* strategy) { strategy_ = strategy; }
int executeStrategy(int a, int b) const {
if (strategy_) return strategy_->execute(a, b);
return 0;
}
private:
const IStrategy* strategy_;
};
int main(int argc, char** argv) {
AddStrategy add;
SubtractStrategy sub;
MultiplyStrategy mul;
Context c(&add);
std::cout << "1 + 2 = " << c.executeStrategy(1, 2) << "\n";
c.setStrategy(&sub);
std::cout << "1 - 2 = " << c.executeStrategy(1, 2) << "\n";
c.setStrategy(&mul);
std::cout << "1 * 2 = " << c.executeStrategy(1, 2) << "\n";
return 0;
}