-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstate.cpp
More file actions
74 lines (65 loc) · 2.02 KB
/
state.cpp
File metadata and controls
74 lines (65 loc) · 2.02 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
65
66
67
68
69
70
71
72
73
74
/*!
* From https://github.com/pezy/DesignPatterns/blob/master/State/main.cpp
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <memory>
// ------------------ State ------------------ //
/*!
* @brief State class
* Defines an interface to encapsulate the behaviour
* associated to a particular state of the Context.
*/
class IWritingState {
public:
virtual void Write(std::string p_words) = 0;
};
// ------------- ConcreteStates ------------- //
/*!
* @brief ConcreteState subclasses
* Implements the behaviour of a particular state of the Context.
*/
class UpperCase : public IWritingState {
public:
void Write(std::string p_words) override {
std::transform(p_words.begin(), p_words.end(), p_words.begin(), ::toupper);
std::cout << p_words << std::endl;
}
};
class LowerCase : public IWritingState {
public:
void Write(std::string p_words) override {
std::transform(p_words.begin(), p_words.end(), p_words.begin(), ::tolower);
std::cout << p_words << std::endl;
}
};
class Default : public IWritingState {
public:
void Write(std::string p_words) override { std::cout << p_words << std::endl; }
};
/*!
* @brief Context
* Interface of interest for the client.
* Maintains a reference to its current state (ConcreteState)
*/
class TextEditor {
public:
TextEditor(const std::shared_ptr<IWritingState>& p_state): m_state(p_state) {}
void SetState(const std::shared_ptr<IWritingState>& p_state) { m_state = p_state; }
void Type(const std::string& p_words) { m_state->Write(p_words); }
private:
std::shared_ptr<IWritingState> m_state; /*!< Current state */
};
// --------------- Client code --------------- //
int main()
{
TextEditor editor(std::make_shared<Default>());
editor.Type("First line");
editor.SetState(std::make_shared<UpperCase>());
editor.Type("Second line");
editor.Type("Third line");
editor.SetState(std::make_shared<LowerCase>());
editor.Type("Fourth line");
editor.Type("Fifth line");
}