假设我们有最简单的结构、Component
类Leaf : Component
和Composite : Component
。类的每个对象Leaf
都有一个int id
赋予它身份的对象。复合类将具有以下内容:
class Composite : public Component
{
public:
void removeComponent(Component*);
// other stuff
private:
std::vector<Component*> coll;
};
和叶子类的东西像:
class Leaf : public Component
{
public:
//stuff
int getID();
private:
int id;
};
问题是如何定义函数removeComponent(Component* cmp)
。cmp 实际上是 a Leaf
,但我需要访问Component
向量 coll,所以它必须是 a Component
(我认为)。removeComponent 方法接受一个Leaf
对象,并从整个结构中移除所有其他具有相同 ID 的叶子。
现在,我想到了两种方法(这两种方法都不起作用:P):
第一的
void Composide::removeComponent(Component* cmp)
{
std::vector<Component*>::const_iterator it;
for(it = coll.begin(); it != coll.end(); ++it)
{
(*it)->removeComponent(cmp);
// where removeComponent is defined as virtual in Component, but
// the problem is that Leaf cannot erase itself from the collection
}
}
第二
void Composide::removeComponent(Component* cmp)
{
std::vector<Component*>::const_iterator it;
for(it = coll.begin(); it != coll.end(); ++it)
{
if((*it)->equals(*cmp))
it = erase(it);
// But here I can't define equals function for Composite elements,
// so then I'd have to make functions which return the type of Component,
// and in case of Composite call recursively the function and
// in the case of Leaf call the equals() function and erase if needed.
// This however looks like really bad OOP practice, and I'd like to avoid
// using those methods which return type..
}
}
必须有一个整洁、漂亮的方法来做到这一点。我有点认为该方法应该看起来像上面提到的第一种方法,只是我真的不知道如何启用Leaf
从向量中删除自身。请帮帮我?:)