



class Graphic
{
public:
virtual ~Graphic();
virtual void Draw(const Point& at) = 0;
virtual void HandleMouse( Event& event) = 0;
virtual const Point& GetExtent() = 0;
virtual void Load(istream& from) = 0;
virtual void Save(ostream& to) = 0;
protected:
Graphic();
};
// Image类实现了Graphic接口用来显示图像文件的接口。
// 同时,实现了Handlemouse操作,使得用户可以交互第调整图像的尺寸。
class Image : public Graphic
{
public:
Image(const char* file);
virtual void Draw(const Point& at);
virtual void HandleMouse( Event& event);
virtual const Point& GetExtent();
virtual void Load(istream& from);
virtual void Save(ostream& to);
protected:
// ....
}
// ImageProxy和Image具有相同的接口
class ImageProxy : public Graphic
{
public:
virtual ~ImageProxy();
virtual void Draw(const Point& at);
virtual void HandleMouse( Event& event);
virtual const Point& GetExtent();
virtual void Load(istream& from);
virtual void Save(ostream& to);
protected:
Image* GetImage();
private:
Image* _image;
Point _extent;
char* _fileName;
};
// 构造函数保存了存储图像的文件名的本地拷贝,并初始化_extent和_image
ImageProxy::ImageProxy (const char* fileName) {
_fileName = strdup(fileName);
_extent = Point::Zero;
_image = 0;
}
Image* ImageProxy::GetImage() {
if (_image == 0) {
_image = new Image(_fileName);
}
}
// GetExtent返回缓存的图像尺寸,否则从文件中装载图像。
const Point& ImageProxy::GetExtent () {
if (_extent == Point::Zero) {
_extent = GetImage()->GetExtent();
}
return _extent;
}
// Draw用来装载图像
void ImageProxy::Draw (const Point& at) {
GetImage()->Draw(at);
}
// HandleMouse
void ImageProxy::HandleMouse (Event& event) {
GetImage()->HandleMouse(event);
}
// Save操作将缓存的图像尺寸和文件名保存在一个流中
void ImageProxy::Save (ostream& to) {
to << _extent << _fileName;
}
// Load得到这个信息并初始化相应的成员函数
void ImageProxy::Load (istream& from) {
from >> _extent >> _fileName;
}
// 假设有一个client,包含Graphic对象
class TextDocument {
public:
TextDocument();
void Insert(Graphic*);
};TextDocument* text = new TextDocument;
// ...
text->Insert(new ImageProxy("anImageFileName"));原文:http://blog.csdn.net/zs634134578/article/details/19028467