mardi 15 février 2022

Change the state of an object according to the state of the other objects

According to this main:

int main() {
    Worker* w1 = new Worker();
    Worker* w2 = new Worker();
    Worker* w3 = new Worker();
    Worker* w4 = new Worker();
    w1->worksWhen(w2, w3); // When w1 works then w2 & w3 starts working
    w2->worksWhen(w1, w3, w4); // When w2 works then w1 & w3  & w4 starts working
    w1->work(); // So that - w2 & w3 is working because w1 works now
    return 0;
}  

How should we write the Worker class? I try with this:

class Observable;
class Observer {
public:
    virtual void update(Observable& o)=0;
};

class Observable {
    list<Observer*> observers;
public:
    void addObserver(Observer& o)  {
        observers.push_back(&o);
    }
    void notify() {
        list<Observer*>::iterator it = observers.begin();
        while (it != observers.end()) {
            (*it)->update(*this);
            it++;
        }
    }
};

class Worker : public Observable {
    bool working;
public:
    Worker() {
        working = false;
    }
    bool isWorking() {
        return working;
    }
    void worksWhen() {
        
    }
    void work() {
        this->working = true;
        notify();
    }
};

My question is: How can I get in worksWhen sometimes 2 arguments of Worker and sometimes 3 arguments of Worker, what should I receive in the worksWhen function and how can I update all the state of the other workers?

Aucun commentaire:

Enregistrer un commentaire