
#include <iostream>
#include <map>
using namespace std;
//Subject
class Graphic {
protected:
string fileName;
public:
virtual void draw() = 0;
string getFileName() {
return fileName;
}
};
//RealSubject
class Image: public Graphic {
public:
Image(string fileName) {
this->fileName = fileName;
}
//Request()
void draw() {
cout << "draw " + fileName + "\n";
}
};
//Proxy
class ImageProxy: public Graphic {
private:
Image *image = NULL;
Image getImage() {
if (image == NULL) {
image = new Image(fileName);
}
return *image;
}
public:
ImageProxy(string fileName) {
this->fileName = fileName;
}
void draw() {
getImage().draw();
}
};
//Client
ImageProxy proxy("1.png");
//operation without creating a RealSubject
string fileName = proxy.getFileName();
//forwarded to the RealSubject
proxy.draw();
cout << "fileName: " << fileName;
| Подменяет другой объект для контроля доступа к нему. Заместитель реализует интерфейс первоначального объекта. |