子对象不会在观察者设计模式的 update() 函数中传递



我正试图将观察员模式集成到我的基于FreeRTOS的嵌入式应用程序中,并根据观察员订阅的内容向他们发送通知。

SysTsk::mainThread是接受用户输入的线程;附上";或";分离";某些通知。这个部分在这里没有必要,所以我没有包括太多。

看起来设计确实有效,但存在一个问题,即void update(Subject *subject)中的subject指针与SensorA类本身不对应,而是Subject和地址在if条件下不匹配。

//observer.hpp
class Subject;
class Observer 
{
public:
virtual ~Observer() = default;
virtual void update(Subject*) = 0;
};

// subject.hpp
static uint8_t constexpr observerMaxSize = 3;
class Observer;
class Subject 
{   
uint8_t headIdx = 0;          // the max index till observers are populated in the buffer
uint8_t tailIdx = 0;    
public:
virtual ~Subject() = default;

Observer *observerList[observerMaxSize];
void attach(Observer *obs);
void detach(Observer *obs);
void notify(Subject*);
};
// notification.hpp
class Notification : public Observer
{
SensorA &_subject;
public:
Notification(SensorA &sensorA);
void update(Subject *subject);
// ...
};
// subject.cpp
void Subject::notify(Subject *subject) 
{
for (uint8_t idx = 0; idx < headIdx; idx++)
{
observerList[idx]->update(subject);
}
}
// sensorA.cpp
class SensorA : public Subject {
public:
void notify() {
for (uint8_t i = 0; i < observerSize; i++) { 
observerList[i]->update(this);
}
};
void SensorA::readVal() {     // invokes within the interrupt
process();
notify();  // Subject::notify()
}
void SensorA::mainThread(void) {
while(true) {
uint16_t data = initiateReadI2C();  
}
}

// notification.cpp
class Notification : public Observer {
public: 
Notification::Notification(SensorA sensorA) : _subject(sensorA) {
_subject.attach(this);  
}
void update(Subject *subject) {
if (subject == &_subject) {    // making sure the notification is received from sensorA to process it accordingly but the address doesn't match

} 
};

// system.cpp - main thread that process user inputs
void SysTsk::mainThread(void){
while(true) {
if (xQueueReceive(sysTskQueue, &msg, 0) == pdPASS)  // user input passed via Queue from ISR {
// parse user input
}
}
}

这很奇怪。当执行到以下代码时,_subject似乎有一个奇怪的地址

void update(Subject *subject) {
if (subject == &_subject) {    // making sure the notification is received from sensorA to process it accordingly but the address doesn't match

}

直到我在函数的开头添加了一些不必要的额外代码行

void update(Subject *subject) {
int random = 0;
if (subject == &_subject) {    // making sure the notification is received from sensorA to process it accordingly but the address doesn't match
random++;      
}
random += 5;
}

Does anyone see why would that be?

最新更新