包含对象和容器的容器

Container containing Objects and Containers

本文关键字:对象 包含      更新时间:2023-10-16

我试图创建一个结构,将被迭代跨越和存储在它的对象将按顺序从左到右绘制。但是会有容器存储在可绘制对象的旁边。我将这些容器视为绘图堆栈,其中可绘制的对象被绘制在彼此的顶部。我有一些粗糙的伪代码写起来,但我不能拿出一个共同的接口,我的容器和可绘制的对象继承。我的目标是在容器和可绘制对象之间建立一个公共接口。我认为我可以通过插入容器来做到这一点,即使它们里面只有一个可绘制的对象,我觉得这只会占用更多的内存并降低速度。我也不希望为了获得正确的调用而避免强制转换对象。有人可以建议我应该做什么,我不是最先进的程序员,但我努力为速度和代码减少。以下是我到目前为止所做的(我知道一些接口调用与依赖项不匹配,我只是不知道该怎么做):

class IDrawable {
  protected:
    signal_t sig; // this is an enumeration
  public:
    void paint(QPainter &painter); // This functionality will be defined here since it is painting to a pixmap
    virtual void reset() = 0;
    virtual void init() = 0; // Setup code will go here
    virtual void update(float) = 0;
};
class Signal : public virtual IDrawable {
  private:
    bool state; // By default this will be false
  public:
    Signal();
    virtual ~Signal();
    // Parameters for update is 0 or 1, since the graphic is just toggled on or off
    virtual void update(float) = 0; // Drawing happens here. Will draw to pixmap
    bool state() {return state;}
};
class Gage : public virtual IDrawable {
  private:
    float cur_val;
  public:
    Gage();
    virtual ~Gage();
    virtual void init() = 0; // Setup code will go here
    virtual void update(float) = 0; // Drawing happens here. Will draw to pixmap
};
class TextGage : public virtual Gage {
  public:
    TextGage();
    virtual ~TextGage();
    void update(float); // Define update functionality here
};
// a stack can coexist with a Gage object in a container
class DrawableStack : public virtual IDrawable {
  private:
    QMap<signal_t, IDrawable*> *Stack;
  public:
    DrawableStack();
    virtual ~DrawableStack();
    void init() {
        Stack = new QMap<signal_t, IDrawable*>();
    }
    void update(signal_t,float); // Drawing happens here. Will draw to pixmap
    void setStack(QMap<IDrawable*> *gageStack) {
        Stack = gageStack;
    }
    void push(IDrawable* node) {
        Stack.insert(node->sigType, node);
    }
};

这是您需要应用的经典复合设计模式:

http://en.wikipedia.org/wiki/Composite_pattern

我想你要找的是复合模式