设计模式之Proxy模式

为其他对象提供一种代理以控制对这个对象的访问。

实现

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
// 抽象主题类
class Subject {
public:
virtual void request() = 0;
};

// 具体主题类
class RealSubject : public Subject {
public:
void request() override {
// ...
}
};

// 代理类
class Proxy : public Subject {
public:
Proxy(Subject* subject) : subject_(subject) {}

void request() override {
if (checkAccess()) {
subject_->request();
logRequest();
}
}

bool checkAccess() {
// ...
}

void logRequest() {
// ...
}

private:
Subject* subject_;
};

int main() {
Subject* realSubject = new RealSubject();
Subject* proxy = new Proxy(realSubject);

proxy->request();

return 0;
}