-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConceptualExample.cpp
More file actions
64 lines (50 loc) · 1.66 KB
/
Copy pathConceptualExample.cpp
File metadata and controls
64 lines (50 loc) · 1.66 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
59
60
61
62
63
64
// ===========================================================================
// ConceptualExample.cpp // State Pattern
// ===========================================================================
#include "ConceptualExample.h"
#include <iostream>
#include <memory>
#include <print>
#include <string>
// very simple example of state pattern
namespace ConceptualExample {
Context::Context(std::unique_ptr<StateBase> state)
{
setState(std::move(state)); // transfer of ownership
}
void Context::request()
{
if (m_state) {
m_state->handle(*this); // use passing by reference
}
}
void Context::setState(std::unique_ptr<StateBase> state)
{
m_state = std::move(state);
std::println("Current state: {}", m_state->getDescription());
}
void ConcreteStateA::handle(Context& context)
{
// generate the next state and pass it to the context.
context.setState(std::make_unique<ConcreteStateB>());
}
void ConcreteStateB::handle(Context& context)
{
// generate the next state and pass it to the context.
context.setState(std::make_unique<ConcreteStateA>());
}
}
void test_conceptual_example() {
using namespace ConceptualExample;
// let context simply reside on the stack.
Context context{ std::make_unique<ConcreteStateA>() };
context.request();
context.request();
context.request();
context.request();
context.request();
context.request();
}
// ===========================================================================
// End-of-File
// ===========================================================================