装饰器的核心是“加料”,我往你身上“套”功能,但你还是你,外界并不知道你被套了

就像浏览器发送请求一样,我只需要拿到一个StreamProcesser,把我想发出去的内容交给它即可,至于它被依次套上了Html标签,经过TLS加密,还是IP层的封装,我不关心

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
#include <cstddef>
#include <iostream>
#include <string>
#include <memory>

class StreamProcesser {
public:
virtual void process(std::string input) = 0;
virtual ~StreamProcesser() {}
StreamProcesser(std::shared_ptr<StreamProcesser> next = nullptr) {
m_next = next;
}
protected:
std::shared_ptr<StreamProcesser> m_next;
};

class HtmlGenerator : public StreamProcesser {
public:
using StreamProcesser::StreamProcesser;
void process(std::string input) override {
std::string result = "<" + input + "/>";
m_next->process(result);
}
};

class TLSProcesser : public StreamProcesser {
public:
using StreamProcesser::StreamProcesser;
void process(std::string input) override {
int key = 3;
for(auto& e : input) {
e += key;
}
m_next->process(input);
}
};

class NetProcesser : public StreamProcesser {
public:
using StreamProcesser::StreamProcesser;
void process(std::string input) override {
std::string result = "src:192.168.31.100|dst:192.168.31.1|" + input;
std::cout << result << std::endl;
}
};

int main() {
std::shared_ptr<StreamProcesser> p = std::make_shared<HtmlGenerator>(std::make_shared<TLSProcesser>(std::make_shared<NetProcesser>()));

p->process("hello");

return 0;
}