【发布时间】:2014-09-24 22:28:34
【问题描述】:
当我有一个异构对象的容器时,我正在实现一个体系结构,这些对象可能有或没有一些常见的方法属性。我需要循环它们并应用一些功能,更新一些成员,并通过各种接口调用一些方法。
我已经提出了我认为基于继承的“标准”架构:
#include <vector>
#include <memory>
#include <iostream>
using namespace std;
struct Base {
virtual ~Base() {}
};
struct PositionInterface {
int x = 0;
int y = 0;
virtual ~PositionInterface() {}
};
struct DrawInterface {
void draw() { cout << "Here i am" << endl; }
virtual ~DrawInterface() {}
};
struct ChargeInterface {
int charge = 100;
virtual ~ChargeInterface() {}
};
struct LifeInterface {
int life = 100;
virtual ~LifeInterface() {}
};
struct A: public Base,
public LifeInterface, public PositionInterface {};
struct B: public Base,
public DrawInterface, public PositionInterface, public ChargeInterface {};
int main() {
std::vector<std::shared_ptr<Base>> vec;
vec.push_back(make_shared<A>());
vec.push_back(make_shared<B>());
for (auto & el : vec) {
auto p = dynamic_cast<PositionInterface *>(el.get());
if (p) {
p->x += 10;
p->y -= 10;
}
}
// ..other stuff
for (auto & el : vec) {
auto l = dynamic_cast<LifeInterface *>(el.get());
if (l) {
l->life -= 100;
}
}
// ..other stuff
for (auto & el : vec) {
auto d = dynamic_cast<DrawInterface *>(el.get());
if (d) {
d->draw();
}
}
}
无论如何,我看起来也像一个基于组件的系统。在我看来,这些接口可以是通过组合而不是继承添加的组件。像这样的:
struct A: public Base {
LifeInterface l;
PositionInterface p;
};
但是我怎样才能通过Base对象dynamic_cast的向量循环到正确的界面?
您认为这种架构有什么缺点吗(除了 RTTI 和公共变量 :-))?
【问题讨论】:
-
我不会提供任何公共变量,而只提供用于接口声明的纯虚拟 getter/setter/操作。
标签: c++ oop inheritance interface components