Skip to content

代理模式 (Proxy Pattern)

什么是代理模式?

代理模式(Proxy Pattern)是一种结构型设计模式,它提供了一个对象来代替另一个对象,并控制对原对象的访问。代理对象可以添加额外的逻辑,如延迟初始化、访问控制、日志记录等。

核心思想:通过代理对象控制对真实对象的访问,在访问前后添加额外逻辑。

为什么需要代理模式?

问题场景

假设我们有一个图像加载系统,图像很大,加载很慢:

// 问题:每次访问都加载图像
class Image {
public:
    virtual void display() {
        loadFromFile("large_image.jpg");  // 很慢!
        render();
    }

private:
    void loadFromFile(const std::string& path) {
        // 模拟耗时操作
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }

    void render() {
        std::cout << "Rendering image...\n";
    }
};

// 问题:用户立即看到空白
Image img;
img.display();  // 需要等待2秒

问题: 1. 延迟加载导致用户体验差 2. 无法控制访问 3. 无法添加额外的逻辑

解决方案

使用代理模式:

class ImageProxy : public Image {
public:
    explicit ImageProxy(const std::string& path) : path_(path), loaded_(false) {}

    void display() override {
        if (!loaded_) {
            loadRealImage();  // 延迟加载
        }
        realImage_->display();
    }

private:
    void loadRealImage() {
        realImage_ = std::make_unique<RealImage>(path_);
        loaded_ = true;
    }

    std::unique_ptr<RealImage> realImage_;
    std::string path_;
    bool loaded_;
};

优点: 1. 延迟加载,提高性能 2. 可以添加额外的控制逻辑 3. 对用户透明

模式结构

                    ┌─────────────┐
                    │   Subject   │
                    │  (接口)      │
                    └──────┬──────┘
                           │
           ┌───────────────┼───────────────┐
           │               │               │
    ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
    │  RealObject │ │  Proxy      │ │  Virtual    │
    │  (真实对象) │ │  (代理对象) │ │  (虚拟代理) │
    └─────────────┘ └─────────────┘ └─────────────┘
           │               │               │
           └───────────────┼───────────────┘
                           │
                    ┌────────▼────────┐
                    │    Client       │ ← 客户端
                    └─────────────────┘

代码实现

1. 定义主题接口

#include <memory>
#include <string>
#include <iostream>
#include <chrono>
#include <thread>

class DataSource {
public:
    virtual ~DataSource() = default;
    virtual std::string getData() = 0;
    virtual void setData(const std::string& data) = 0;
};

2. 实现真实对象

class RealDataSource : public DataSource {
public:
    explicit RealDataSource(const std::string& path) : path_(path) {}

    std::string getData() override {
        std::cout << "Loading data from " << path_ << "...\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));  // 模拟延迟
        return "Data from " + path_;
    }

    void setData(const std::string& data) override {
        std::cout << "Saving data to " << path_ << "...\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
        data_ = data;
    }

    std::string getPath() const { return path_; }

private:
    std::string path_;
    std::string data_;
};

3. 实现虚拟代理(延迟加载)

class LazyProxy : public DataSource {
public:
    explicit LazyProxy(const std::string& path) 
        : path_(path), real_(nullptr) {}

    std::string getData() override {
        if (!real_) {
            real_ = std::make_unique<RealDataSource>(path_);
        }
        return real_->getData();
    }

    void setData(const std::string& data) override {
        if (!real_) {
            real_ = std::make_unique<RealDataSource>(path_);
        }
        real_->setData(data);
    }

    bool isLoaded() const { return real_ != nullptr; }

private:
    std::string path_;
    std::unique_ptr<RealDataSource> real_;
};

4. 实现保护代理(访问控制)

class AccessProxy : public DataSource {
public:
    AccessProxy(std::unique_ptr<RealDataSource> real, const std::string& user)
        : real_(std::move(real)), user_(user) {}

    std::string getData() override {
        if (!canRead()) {
            throw std::runtime_error("Access denied for user: " + user_);
        }
        return real_->getData();
    }

    void setData(const std::string& data) override {
        if (!canWrite()) {
            throw std::runtime_error("Write denied for user: " + user_);
        }
        real_->setData(data);
    }

    bool canRead() const {
        return user_ == "admin" || user_ == "editor";
    }

    bool canWrite() const {
        return user_ == "admin";
    }

private:
    std::unique_ptr<RealDataSource> real_;
    std::string user_;
};

5. 实现缓存代理

class CacheProxy : public DataSource {
public:
    explicit CacheProxy(std::unique_ptr<RealDataSource> real)
        : real_(std::move(real)) {}

    std::string getData() override {
        if (cache_.empty()) {
            cache_ = real_->getData();
            std::cout << "[Cache] Data loaded and cached\n";
        } else {
            std::cout << "[Cache] Returning cached data\n";
        }
        return cache_;
    }

    void setData(const std::string& data) override {
        real_->setData(data);
        cache_.clear();  // 失效缓存
        std::cout << "[Cache] Cache invalidated\n";
    }

    void clearCache() {
        cache_.clear();
        std::cout << "[Cache] Cache cleared\n";
    }

    size_t cacheSize() const { return cache_.empty() ? 0 : 1; }

private:
    std::unique_ptr<RealDataSource> real_;
    std::string cache_;
};

6. 客户端使用

int main() {
    std::cout << "=== Lazy Proxy Demo ===\n";
    {
        LazyProxy proxy("data.txt");
        std::cout << "Is loaded: " << proxy.isLoaded() << "\n";
        std::cout << "Data: " << proxy.getData() << "\n";
        std::cout << "Is loaded: " << proxy.isLoaded() << "\n";
    }

    std::cout << "\n=== Access Proxy Demo ===\n";
    {
        auto real = std::make_unique<RealDataSource>("data.txt");
        AccessProxy adminProxy(std::move(real), "admin");
        AccessProxy readerProxy(std::make_unique<RealDataSource>("data.txt"), "reader");

        try {
            std::cout << "Admin data: " << adminProxy.getData() << "\n";
        } catch (const std::exception& e) {
            std::cout << "Error: " << e.what() << "\n";
        }

        try {
            std::cout << "Reader data: " << readerProxy.getData() << "\n";
        } catch (const std::exception& e) {
            std::cout << "Error: " << e.what() << "\n";
        }
    }

    std::cout << "\n=== Cache Proxy Demo ===\n";
    {
        auto real = std::make_unique<RealDataSource>("data.txt");
        CacheProxy proxy(std::move(real));

        std::cout << "First call: " << proxy.getData() << "\n";
        std::cout << "Second call: " << proxy.getData() << "\n";
        proxy.setData("new data");
        std::cout << "After update: " << proxy.getData() << "\n";
    }

    return 0;
}

现代 C++ 实现

使用模板代理

template<typename T>
class Proxy : public T {
public:
    using T::T;  // 继承构造函数

    void logAccess(const std::string& method) const {
        std::cout << "[Proxy] Calling " << method << "\n";
    }
};

使用装饰器式代理

template<typename T>
class LoggingProxy : public T {
public:
    using T::T;

    template<typename... Args>
    auto invoke(const std::string& method, Args&&... args) 
        -> decltype(std::declval<T&>().someMethod(std::forward<Args>(args)...)) {

        std::cout << "[Logging] Calling " << method << "\n";
        auto result = std::invoke(&T::someMethod, *this, std::forward<Args>(args)...);
        std::cout << "[Logging] " << method << " returned\n";
        return result;
    }
};

使用智能指针管理

class SmartProxy {
public:
    template<typename T, typename... Args>
    static std::shared_ptr<T> create(Args&&... args) {
        auto real = std::make_shared<T>(std::forward<Args>(args)...);
        return std::make_shared<LoggingProxy<T>>(real);
    }
};

与相关模式的区别

模式 区别
装饰器模式 装饰器增强功能;代理控制访问
适配器模式 适配器转换接口;代理控制访问
外观模式 外观简化接口;代理控制访问

最佳实践

1. 使用组合而非继承

// 推荐:使用组合
class Proxy {
public:
    explicit Proxy(std::shared_ptr<RealObject> real)
        : real_(std::move(real)) {}

private:
    std::shared_ptr<RealObject> real_;
};

// 不推荐:使用继承(限制了类的层次)
class Proxy : public RealObject { ... };

2. 使用弱引用避免循环依赖

class ObserverProxy {
public:
    void observe(std::weak_ptr<Subject> subject) {
        subject_ = subject;
    }

    void update() {
        if (auto subject = subject_.lock()) {
            subject->notify();
        }
    }

private:
    std::weak_ptr<Subject> subject_;
};

3. 支持多层代理

class MultiProxy {
public:
    void addProxy(std::shared_ptr<Proxy> proxy) {
        proxies_.push_back(std::move(proxy));
    }

    std::string process() {
        std::string result = "original";
        for (const auto& proxy : proxies_) {
            result = proxy->intercept(result);
        }
        return result;
    }

private:
    std::vector<std::shared_ptr<Proxy>> proxies_;
};

常见陷阱

陷阱 1:代理泄漏

// 不推荐:忘记释放代理
void process() {
    Proxy* proxy = new Proxy(real);
    proxy->process();
    // 忘记 delete proxy;
}

// 推荐:使用智能指针
void process() {
    auto proxy = std::make_unique<Proxy>(real);
    proxy->process();
    // 自动释放
}

陷阱 2:代理链过长

// 不推荐:代理嵌套过多
auto proxy1 = std::make_shared<Proxy1>(
    std::make_shared<Proxy2>(
        std::make_shared<Proxy3>(
            std::make_shared<RealObject>()
        )
    )
);

// 推荐:使用代理工厂统一管理
class ProxyFactory {
public:
    static std::shared_ptr<RealObject> create() {
        auto real = std::make_shared<RealObject>();
        return std::make_shared<LoggingProxy>(
            std::make_shared<CacheProxy>(
                std::make_shared<AccessProxy>(real, "admin")
            )
        );
    }
};

陷阱 3:线程安全问题

// 不推荐:非线程安全
class ThreadUnsafeProxy {
public:
    void process() {
        if (!real_) {
            real_ = createReal();  // 可能多线程竞争
        }
        real_->process();
    }

private:
    RealObject* real_ = nullptr;
};

// 推荐:使用线程安全的延迟初始化
class ThreadSafeProxy {
public:
    void process() {
        std::call_once(flag_, [this]() {
            real_ = createReal();
        });
        real_->process();
    }

private:
    std::once_flag flag_;
    std::unique_ptr<RealObject> real_;
};

示例

这个主题的可运行版本:

总结

代理模式的核心要点:

  • 适用场景:延迟加载、访问控制、缓存、日志记录
  • 核心优点:控制访问、添加逻辑、对用户透明
  • 实现要点:使用智能指针、支持多层代理、线程安全
  • 常见陷阱:代理泄漏、链过长、线程安全

记住:代理模式的关键是"控制访问"——通过代理对象控制对真实对象的访问,添加额外的逻辑而不修改原始类。