我需要一些关于 Image 类层次结构的设计建议。
目前,我有两种类型的图像(一种是标准图像,第二种不包含标准图像数据)。有时我希望对象为图像数据分配内存,而其他时候我只想让它指向它。
当我想为 TypeA 图像提供特定功能时,就会出现问题。
如果 TypeA 图像继承自 Image,我将不得不复制 Allocated 与非 Allocated Image 的功能。
我确信有更好的方法可以做到这一点,我记得在大学期间使用 mixins 的一些优雅解决方案,但在这里找不到使用它的方法。
我目前的设计看起来像:
class Image
{
public:
Image(int width, int height, int bpp);
virtual ~Image() {};
// getters
template <typename T>
T* ptr() { return reinterpret_cast<T*>(m_imageData); } // T depends on bpp
protected:
// metadata
char* m_imageData;
};
class AllocImage : public Image
{
public:
AllocImage(int width, int height, int bpp, DataType dataType) :
Image(width, height, bpp, dataType)
{
m_imageData = new char[m_dataSize];
}
~AllocImage()
{
delete m_imageData;
}
};
class ImageHolder : public Image
{
public:
ImageHolder(int width, int height, int bpp, DataType m_dataType);
void setPtr(const void* ptr);
};
class AllocatedImageTypeA : public AllocImage
{
public:
// Type A specific methods
};
class NonAllocatedImageTypeA : public ImageHolder
{
public:
// duplicated Type A specific methods
};