-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.cc
More file actions
58 lines (49 loc) · 1.34 KB
/
Copy pathstrategy.cc
File metadata and controls
58 lines (49 loc) · 1.34 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
53
54
55
56
57
58
// Copyright 2024 JOK Inc. All Rights Reserved.
// Author: easytojoin@163.com (jok)
#include <iostream>
#include <memory>
#include <optional>
#include <string>
class IStrategy {
public:
virtual ~IStrategy() = default;
virtual std::string doSomething() const = 0;
};
class StrategyA : public IStrategy {
public:
std::string doSomething() const override { return "Do strategy from A"; }
};
class StrategyB : public IStrategy {
public:
std::string doSomething() const override { return "Do strategy from B"; }
};
class Context {
public:
explicit Context(std::unique_ptr<IStrategy>&& strategy)
: strategy_(std::move(strategy)) {}
void setStrategy(std::unique_ptr<IStrategy>&& strategy) {
strategy_ = std::move(strategy);
}
std::optional<std::string> makeDecisions() const {
if (strategy_.get() == nullptr) {
std::cout << "Context: no strategy\n";
return std::nullopt;
}
return strategy_->doSomething();
}
private:
std::unique_ptr<IStrategy> strategy_;
};
int main(int argc, char** argv) {
Context c(nullptr);
auto res = c.makeDecisions();
auto val = [&]() { std::cout << res.value_or("nullptr") << "\n"; };
val();
c.setStrategy(std::make_unique<StrategyA>());
res = c.makeDecisions();
val();
c.setStrategy(std::make_unique<StrategyB>());
res = c.makeDecisions();
val();
return 0;
}