-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstatic_strategy.cpp
More file actions
71 lines (59 loc) · 1.81 KB
/
static_strategy.cpp
File metadata and controls
71 lines (59 loc) · 1.81 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
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
enum class OutputFormat { Markdown, Html };
struct ListStrategy {
virtual ~ListStrategy() = default;
virtual void add_list_item(ostringstream &oss, const string &item) = 0;
virtual void start(ostringstream &oss) = 0;
virtual void end(ostringstream &oss) = 0;
};
struct MarkdownListStrategy : ListStrategy {
// NOTE: There is no dynamic polymorphism, thus we are forced to implement the
// start() and end() methods.
void start(ostringstream &) override {}
void end(ostringstream &) override {}
void add_list_item(ostringstream &oss, const string &item) override {
oss << " * " << item << endl;
}
};
struct HtmlListStrategy : ListStrategy {
void start(ostringstream &oss) override { oss << "<ul>" << endl; }
void end(ostringstream &oss) override { oss << "</ul>" << endl; }
void add_list_item(ostringstream &oss, const string &item) override {
oss << "<li>" << item << "</li>" << endl;
}
};
// template allows to define the strategy statically.
// however, we cannot switch at runtime.
template <typename LS> struct TextProcessor {
void clear() {
oss.str("");
oss.clear();
}
void append_list(const vector<string> &items) {
list_strategy.start(oss);
for (auto &item : items)
list_strategy.add_list_item(oss, item);
list_strategy.end(oss);
}
string str() const { return oss.str(); }
private:
ostringstream oss;
// pointer/reference is not needed anymore.
LS list_strategy;
};
int main() {
// markdown
TextProcessor<MarkdownListStrategy> tpm;
tpm.append_list({"foo", "bar", "baz"});
cout << tpm.str() << endl;
// html
TextProcessor<HtmlListStrategy> tph;
tph.append_list({"foo", "bar", "baz"});
cout << tph.str() << endl;
return 0;
}