#include <iostream>
#include <memory>
#include <string>

// Abstract Subject: Defines common interface for RealSubject and Proxy
class Image {
public:
    virtual void display() = 0;
    virtual ~Image() = default;
};

// Real Subject: The actual object that performs the work, simulates expensive load operation in constructor
class RealImage : public Image {
    std::string filename;

    void loadFromDisk() {
        std::cout << "Loading image from disk: " << filename << std::endl;
    }

public:
    explicit RealImage(const std::string& file) : filename(file) {
        loadFromDisk();  // Load immediately on construction (time-consuming operation)
    }

    void display() override {
        std::cout << "Displaying image: " << filename << std::endl;
    }
};

// Proxy: Controls access to RealImage, implements lazy loading
class ProxyImage : public Image {
    std::string filename;
    std::unique_ptr<RealImage> realImage;  // Initially null

public:
    explicit ProxyImage(const std::string& file) : filename(file) {}

    void display() override {
        // Only create RealImage on first display() call
        if (!realImage) {
            realImage = std::make_unique<RealImage>(filename);
        }
        realImage->display();
    }
};

// 客户端代码
int main() {
    // 创建代理,此时不会加载图片
    ProxyImage proxy("photo.jpg");
    std::cout << "Proxy created, image not loaded yet.\n" << std::endl;

    // 第一次显示:触发加载,然后显示
    std::cout << "First call to display():" << std::endl;
    proxy.display();

    std::cout << "\nSecond call to display():" << std::endl;
    // 第二次显示:直接使用已加载的真实对象,不再重复加载
    proxy.display();

    return 0;
}

results matching ""

    No results matching ""