首先,抱歉标题。我不确切知道如何为我所面临的情况命名。 我正在使用C ++开发一个将在QNX上运行的项目(因此,重复使用Windows库的答案并不好)。
我有一个类来保存和操作我的所有数据,还有一些其他类负责处理我的UI。
UI操作类包括我的数据类,当它们被初始化时,它们都获得指向同一数据对象的指针(尽管每个数据对象使用不同的部分)。并且程序的正常流程是UI从用户接收事件,然后根据数据类回复调用数据类并更新自身。一切正常。
问题是,有时可能会发生这个数据类对象从其他类型的外部事件接收调用(假设来自负责通信的类的调用),要求它更改其中的一些值。这样做之后,它必须更新UI(因此,必须调用UI类)。
所有类(UI和数据)的实际对象都包含在“main”类中。但是由于UI类包含能够调用它的方法的数据类,因此包含UI类的数据类将能够调用它们的方法,这将属于相互包容。
问题以一种非常简单的方式(我只是试图给出一个信息流的可视化示例)恢复到这样的事情:
的main.cpp
#include "interface.h"
#include "data.h"
Data data_;
Interface interface_;
// Initialize all data from files, etc
data_.Init();
// Call the interface that will use all of this data
interface_.Init(&data_);
while(1);
interface.h
#include "data.h"
class Interface
{
Data *data_;
void Init(Data *data);
void ReceiveEvent();
void ChangeScreen (int value);
};
interface.cpp
#include "interface.h"
void Interface::Init(Data *data)
{
// Get the pointer locally
data_ = data;
}
// Function called when a (for example) a touch screen input is triggered
void Interface::ReceiveEvent()
{
ChangeScreen(data_->IncreaseParam1());
}
void Interface::ChangeScreen (int value);
{
// Set the value on screen
}
data.h
class Data
{
int param 1;
void Init();
int IncreaseParam1();
void ReceiveExternalEvent();
};
** data.cpp“
#include "data.h"
void Data::Init()
{
// The value actually come from file, but this is enough for my example
param1 = 5;
}
int IncreaseParam1()
{
param1 += 5;
return param1;
}
// This is called from (for example) a communication class that has a
// pointer to the same object that the interface class object has
void ReceiveExternalEvent()
{
IncreaseParam1();
// NOW HERE IT WOULD HAVE TO CALL A METHOD TO UPDATE THE INTERFACE
// WITH THE NEW PARAM1 VALUE!
}
我希望自己足够清楚。
有人可以就如何处理这种情况向我提出想法吗? 非常感谢提前!
答案 0 :(得分:0)
Data
和Interface
都是单身人士。您希望每个类只有一个实例。所以:
Class Data {
public:
static Data *instance;
Data()
{
instance=this;
}
// Everything else that goes into Data, etc...
};
Class Interface {
public:
static Interface *instance;
Interface()
{
instance=this;
}
// Everything else that goes into Data, etc...
};
现在,ReceiveExternalEvent()
只会调用Data::instance->method()
和/或Interface::instance->method()
,依此类推......
这是一种经典的单例设计模式。
此外,您可能会发现一些您可能感兴趣的其他Google食物:"模型视图控制器"和" mvc"。