13.委托相关设计

1.例子1
image

2.例子2
Prototype Pattern原型,核心思想是:
用一个已经创建好的对象(原型)作为模板,通过拷贝(clone)它来创建新对象,而不是每次都用 new + 构造函数参数去创建。
image
最上面的 Prototype 类:Image(抽象基类)
class Image {
public:
virtual Image* clone() = 0; // 纯虚函数:强制子类实现拷贝自己
virtual ~Image() = default; // 虚析构

static Image* findAndClone(int type);        // 关键静态函数
static void addPrototype(Image* pImage);     // 添加新原型

private:
static Image* prototypes[10]; // 存放所有原型对象(最多10种)
// 实际代码可能用 vector 或 map,更灵活
};
prototypes[] 数组:存放所有“原型对象”(已经创建好的模板对象)。
addPrototype(pImage):把一个原型对象加入数组(通常在程序启动时做)。
findAndClone(type):根据类型 ID,找到对应原型,然后调用它的 clone() 来拷贝出一个新对象。

Image* Image::findAndClone(int i) {
return prototypes[i]->clone(); // 委托给原型自己去 clone
}

下面的两个具体类:LandSatImage 和 SpotImage
它们都继承自 Image,并实现了自己的 clone():
class LandSatImage : public Image {
public:
LandSatImage(); // 正常构造(可能很耗时)
LandSatImage(int) { } // 哑构造函数(dummy)

Image* clone() override {
    return new LandSatImage(1);          // 拷贝自己(这里用哑构造函数)
}

// 程序启动时,把自己作为一个原型加入
static LandSatImage LSAT;                // 静态对象

};

LandSatImage LandSatImage::LSAT; // 定义静态原型对象
// 在某个初始化函数里:
Image::addPrototype(&LandSatImage::LSAT); // 把 this 加入原型数组
SpotImage 同理。

posted @ 2026-01-06 14:48  r5ett  阅读(1)  评论(0)    收藏  举报