41 lines
937 B
C++
41 lines
937 B
C++
/**
|
|
* @name 代理模式
|
|
* @brief: 为其他对象提供代理以控制访问
|
|
* @note 场景:延迟加载、访问控制、远程代理
|
|
*/
|
|
|
|
class Image {
|
|
public:
|
|
virtual void display() = 0;
|
|
};
|
|
|
|
class RealImage : public Image {
|
|
public:
|
|
RealImage(const std::string& file) : filename(file) { load(); }
|
|
void display() override { /* 显示图片 */ }
|
|
private:
|
|
void load() { /* 耗时加载操作 */ }
|
|
std::string filename;
|
|
};
|
|
|
|
class ProxyImage : public Image {
|
|
public:
|
|
ProxyImage(const std::string& file) : filename(file) {}
|
|
void display() override {
|
|
if (!realImage) {
|
|
realImage = new RealImage(filename);
|
|
}
|
|
realImage->display();
|
|
}
|
|
private:
|
|
RealImage* realImage = nullptr;
|
|
std::string filename;
|
|
};
|
|
|
|
// 使用
|
|
int main()
|
|
{
|
|
Image* image = new ProxyImage("large_photo.jpg");
|
|
// 此时未加载真实图片
|
|
image->display(); // 首次访问时加载
|
|
} |