vendredi 18 juin 2021

Subscribing dynamic number of subjects inside an observer class without using dynamic allocation

I am trying to implement an observer design pattern to accommodate a case where I could subscribe notifications from the specific sensors every time their values are read.

So I came up with a design where I have a Notification class as an observer with respective Sensor class(es) as Subjects.

When the Notification class is instantiated, the passed-in subject subscribes to the notifications so every time the Sensor value is read, notify() is invoked which calls update() of each observer from the observer list.

Concern:

  • In order to subscribe to multiple sensors (subjects) for notifications (observer), I should be having a fixed-size buffer inside the Notification class (trying to avoid dynamic allocation) that holds the active subjects in it, but how would I pass in however many subjects I want the observer to get notified for given I want to attach all at once inside a Notification constructor?
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*);
};

class Subject;

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

class SensorA : public Subject {

};

class Notification : public Observer {
    Subject &_sub;
    public:
    Notification(Subject &sub) : _sub(sub) {
       _sub.attach(this);    // subscribing "sub" for notifications, but how to have multiple subs attach "this"? 
    }

};

int main(void) {

   SensorA a;
   Notification ntf(a);

}

Aucun commentaire:

Enregistrer un commentaire