这是我对此的第一个问题,所以请容忍我。
我们开发了一个收集数据的应用程序,我们有一些方法可以让我们以各种方式可视化数据。随着越来越多的方法,我们决定将应用程序和可视化方法分开。我想知道什么是实现这一目标的最佳方法。我想出了下面的代码,它试图将两者分开,但是.
有更好的方法吗?
// forward declaration
class App;
// Interface to all visualization methods
struct Methods {
virtual void show(App * a) = 0;
};
// Some visualization method
struct Method0 : public Methods {
void show(App * a) {
a->getData();
}
};
class App {
public:
vector<Methods *> methods;
void run() {
// draw all registered methods
for (auto m : methods)
m->show(this);
}
int getData() {
// parse and precompute data (time-consuming, thus do it only once)
// return the required data (not just an int..)
return 42;
}
};
void main() {
App a;
// register some methods
a.methods.push_back(new Method0());
// run the application
a.run();
// clean up
for (auto m : a.methods) delete(m);
}编辑
我想亚历山大和彼特给我指明了正确的方向,谢谢。我将遵循Petr的建议,尝试将数据分离到另一个类中。
在谈到Spektre的评论时:
数据是一组包含其他对象向量的对象向量,共5个维。
一个可视化类似于ROC曲线,包含几条曲线,因此我们需要遍历部分/所有维数并计算一些统计数据。结果如下图所示。

发布于 2015-05-26 09:13:48
除了Alexander的回答之外,我要提到的是,实际上您并没有将数据和可视化完全分开。Application类仍然知道数据的内部结构和可视化方法的向量。您最好做的是有一个单独的类,比如Data,它将执行所需的所有计算,然后拥有主类(例如,App),它将处理方法的注册并将数据传递给它们。
有点像
class Data;
struct Methods {
virtual void show(Data * a) = 0;
};
struct Method0 : public Methods {
void show(Data * d) {
d->getData();
}
};
class Data {
public:
int getData() {
// parse and precompute data (time-consuming, thus do it only once)
// return the required data (not just an int..)
return 42;
}
}
class App {
public:
vector<Methods *> methods;
Data* data;
void run() {
// draw all registered methods
for (auto m : methods)
m->show(data);
}
};发布于 2015-05-26 07:49:32
你那里的东西看上去已经很不错了。正如你可能已经假设的那样,你不是第一个有这种问题的人。将您的数据与可视化分离的标准解决方案称为模型视图控制器模式(MVC),它不仅将数据的表示与数据本身分离,而且还允许对数据进行简单的显示操作。
如果您只想显示您的数据,那么您可能需要查看一下观测器模式。再说一遍,你所拥有的已经非常接近这个模式了。
https://stackoverflow.com/questions/30452352
复制相似问题