-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.cpp
More file actions
51 lines (45 loc) · 1.2 KB
/
strategy.cpp
File metadata and controls
51 lines (45 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
// The Strategy Design Pattern
#include <iostream>
#include <memory>
// A flexible payment strategy containing many options
class PaymentStrategy {
public:
virtual ~PaymentStrategy() = default;
virtual std::string withdraw(double amount) = 0;
};
// This class behaves like the context - can choose any strategy
class Customer {
// private members
std::unique_ptr<PaymentStrategy> strategy_;
public:
explicit Customer(std::unique_ptr<PaymentStrategy> &&strategy) : strategy_(std::move(strategy)) // use rvalue ref constructor to be flexible
{
}
void pay(double amount) {
std::cout << "Paying " << amount << " dollars using " << strategy_->withdraw(amount) << "\n";
}
};
// Various concrete strategies...
class CreditCard : public PaymentStrategy {
public:
std::string withdraw(double amount) {
return "credit card";
}
};
class DebitCard : public PaymentStrategy {
public:
std::string withdraw(double amount) {
return "debit card";
}
};
class Cash : public PaymentStrategy {
public:
std::string withdraw(double amount) {
return "cash";
}
};
int main() {
Customer Bob(std::make_unique<CreditCard>());
Bob.pay(100);
return 0;
}