Skip to content

Commit acf6410

Browse files
committed
[STATE]: Added sample code for State pattern.
1 parent ac8a8e6 commit acf6410

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

behavioral-patterns/state/state.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*!
2+
* From https://github.com/pezy/DesignPatterns/blob/master/State/main.cpp
3+
*/
4+
5+
#include <iostream>
6+
#include <string>
7+
#include <algorithm>
8+
#include <memory>
9+
10+
class IWritingState {
11+
public:
12+
virtual void Write(std::string p_words) = 0;
13+
};
14+
15+
class UpperCase : public IWritingState {
16+
void Write(std::string p_words) override {
17+
std::transform(p_words.begin(), p_words.end(), p_words.begin(), ::toupper);
18+
std::cout << p_words << std::endl;
19+
}
20+
};
21+
22+
class LowerCase : public IWritingState {
23+
void Write(std::string p_words) override {
24+
std::transform(p_words.begin(), p_words.end(), p_words.begin(), ::tolower);
25+
std::cout << p_words << std::endl;
26+
}
27+
};
28+
29+
class Default : public IWritingState {
30+
void Write(std::string p_words) override { std::cout << p_words << std::endl; }
31+
};
32+
33+
class TextEditor {
34+
public:
35+
TextEditor(const std::shared_ptr<IWritingState>& p_state): m_state(p_state) {}
36+
void SetState(const std::shared_ptr<IWritingState>& p_state) { m_state = p_state; }
37+
void Type(const std::string& p_words) { m_state->Write(p_words); }
38+
private:
39+
std::shared_ptr<IWritingState> m_state;
40+
};
41+
42+
int main()
43+
{
44+
TextEditor editor(std::make_shared<Default>());
45+
editor.Type("First line");
46+
47+
editor.SetState(std::make_shared<UpperCase>());
48+
editor.Type("Second line");
49+
editor.Type("Third line");
50+
51+
editor.SetState(std::make_shared<LowerCase>());
52+
editor.Type("Fourth line");
53+
editor.Type("Fifth line");
54+
}

0 commit comments

Comments
 (0)