-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConceptualExample02.cpp
More file actions
61 lines (47 loc) · 1.65 KB
/
ConceptualExample02.cpp
File metadata and controls
61 lines (47 loc) · 1.65 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
// ===========================================================================
// ConceptualExample02.cpp // State Pattern
// ===========================================================================
#include <iostream>
#include <string>
#include <memory>
#include "ConceptualExample02.h"
// very simple example of state pattern
namespace ConceptualExample02 {
Context::Context(std::shared_ptr<StateBase> state)
{
setState(state);
}
void Context::request()
{
m_state->handle(shared_from_this());
}
void Context::setState(std::shared_ptr<StateBase> base)
{
m_state = base;
std::cout << "Current state: " << m_state->getDescription() << std::endl;
}
void ConcreteStateA::handle(std::shared_ptr<Context> context)
{
std::shared_ptr<StateBase> newState{ std::make_shared<ConcreteStateB>() };
context->setState(newState);
}
void ConcreteStateB::handle(std::shared_ptr<Context> context)
{
std::shared_ptr<StateBase> newState{ std::make_shared<ConcreteStateA>() };
context->setState(newState);
}
}
void test_conceptual_example_02() {
using namespace ConceptualExample02;
std::shared_ptr<StateBase> initialState{ std::make_shared<ConcreteStateA>() };
std::shared_ptr<Context> context{ std::make_shared<Context>(initialState) };
context->request();
context->request();
context->request();
context->request();
context->request();
context->request();
}
// ===========================================================================
// End-of-File
// ===========================================================================