From f00a7d284e2359e38d6f210e0f1a8af4fea3124e Mon Sep 17 00:00:00 2001 From: Yuki Date: Sun, 13 Apr 2025 17:05:57 +0800 Subject: [PATCH] feat: Proxy Implemented a demo for the Proxy. --- 13_proxy.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ notes.md | 6 +++++ 2 files changed, 69 insertions(+) create mode 100644 13_proxy.cpp diff --git a/13_proxy.cpp b/13_proxy.cpp new file mode 100644 index 0000000..7671b98 --- /dev/null +++ b/13_proxy.cpp @@ -0,0 +1,63 @@ +#include +#include + + +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 rs; + const string role; +public: + UserServiceProxy(const string& s) : role(s) { + rs = make_shared(); + } + + 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(); +} diff --git a/notes.md b/notes.md index 98c78e7..e9c660e 100644 --- a/notes.md +++ b/notes.md @@ -83,3 +83,9 @@ 在创建同一类的大量对象实例时,往往会面临内存占用过高的问题。这种情况的一个常见原因是:对象实例中包含了大量冗余的、可以共享的数据。例如,在游戏开发中,多个实体可能共用相同的模型和贴图资源。如果每个实例都独立持有这些资源,就会造成不必要的内存浪费。 为了解决这一问题,享元模式提供了一种有效的解决方案。它的核心思想是将对象的数据划分为可共享的和不可共享的。在实现过程中,享元模式通常通过一个享元工厂来统一管理和缓存内部状态。当需要创建新对象时,工厂会首先检查是否已有对应的内部状态资源,若有则复用,从而避免重复实例化共享部分,显著降低内存开销。 + +## 代理模式(Proxy) + +我们在使用一个类时,有时会觉得这个类的功能较简单,实际使用需要额外添加一些访问控制,缓存管理等功能。简单的想法是直接在这个类中添加这些功能,但这会使得这个类急剧膨胀,且核心功能变得不那么明确。 + +代理模式解决了这个问题。通过一个代理类实现目标类相同接口,客户端使用代理时就像在直接操作目标类。代理类内部有目标类的指针,在处理缓存、权限等逻辑后再去调用目标类的相关函数,从而做到外围与核心逻辑的分离。