feat: Proxy

Implemented a demo for the Proxy.
This commit is contained in:
Yuki 2025-04-13 17:05:57 +08:00
parent 11df3146d7
commit f00a7d284e
Signed by: yuki
GPG Key ID: CF40579331C06C73
2 changed files with 69 additions and 0 deletions

63
13_proxy.cpp Normal file
View File

@ -0,0 +1,63 @@
#include <iostream>
#include <memory>
using namespace std;
class Service {
public:
virtual int read() = 0;
virtual int write() = 0;
virtual ~Service() = default;
};
class RawService : public Service {
public:
virtual int read() override {
cout << "read succeed" << endl;
return 1;
}
virtual int write() override {
cout << "write succeed" << endl;
return 1;
}
};
// Inherit from the same interface to so that the proxy class
// and the target class can be used in the same way.
class UserServiceProxy : public Service {
// Use pointers instead of inheritance to reduce coupling.
shared_ptr<RawService> rs;
const string role;
public:
UserServiceProxy(const string& s) : role(s) {
rs = make_shared<RawService>();
}
virtual int read() override {
return rs->read();
}
virtual int write() override {
// Implement peripheral logic here, separating it from the core logic.
if (role != "admin") {
cout << "write failed: permission denied" << endl;
return 0;
}
return rs->write();
}
};
int main() {
UserServiceProxy admin("admin");
admin.read();
admin.write();
UserServiceProxy user("user");
user.read();
user.write();
}

View File

@ -83,3 +83,9 @@
在创建同一类的大量对象实例时,往往会面临内存占用过高的问题。这种情况的一个常见原因是:对象实例中包含了大量冗余的、可以共享的数据。例如,在游戏开发中,多个实体可能共用相同的模型和贴图资源。如果每个实例都独立持有这些资源,就会造成不必要的内存浪费。 在创建同一类的大量对象实例时,往往会面临内存占用过高的问题。这种情况的一个常见原因是:对象实例中包含了大量冗余的、可以共享的数据。例如,在游戏开发中,多个实体可能共用相同的模型和贴图资源。如果每个实例都独立持有这些资源,就会造成不必要的内存浪费。
为了解决这一问题,享元模式提供了一种有效的解决方案。它的核心思想是将对象的数据划分为可共享的和不可共享的。在实现过程中,享元模式通常通过一个享元工厂来统一管理和缓存内部状态。当需要创建新对象时,工厂会首先检查是否已有对应的内部状态资源,若有则复用,从而避免重复实例化共享部分,显著降低内存开销。 为了解决这一问题,享元模式提供了一种有效的解决方案。它的核心思想是将对象的数据划分为可共享的和不可共享的。在实现过程中,享元模式通常通过一个享元工厂来统一管理和缓存内部状态。当需要创建新对象时,工厂会首先检查是否已有对应的内部状态资源,若有则复用,从而避免重复实例化共享部分,显著降低内存开销。
## 代理模式Proxy
我们在使用一个类时,有时会觉得这个类的功能较简单,实际使用需要额外添加一些访问控制,缓存管理等功能。简单的想法是直接在这个类中添加这些功能,但这会使得这个类急剧膨胀,且核心功能变得不那么明确。
代理模式解决了这个问题。通过一个代理类实现目标类相同接口,客户端使用代理时就像在直接操作目标类。代理类内部有目标类的指针,在处理缓存、权限等逻辑后再去调用目标类的相关函数,从而做到外围与核心逻辑的分离。