Refactor Driver–Bus Relationship

#include <iostream>
using namespace std;

class Bus {
public:
    Bus() {
        cout << "Bus ready" << endl;
    }

    ~Bus() {
        cout << "Bus stopped" << endl;
    }

    void write(int addr, int val) {
        cout << "Bus write: " << addr << " " << val << endl;
    }
};

// WRONG: Each Driver becomes its own Bus
class Driver {
private:
    Bus* bus;
public:
    Driver(Bus* b):bus(b) {
        cout << "Driver started" << endl;
    }

    void operate(int addr, int val) {
        bus->write(addr, val);
    }

    ~Driver() {
        cout << "Driver stopped" << endl;
    }
};

int main() {
    int a1, v1, a2, v2;
    cin >> a1 >> v1 >> a2 >> v2;

    {
        Bus b;
        Driver d1(&b);
        Driver d2(&b);
        d1.operate(a1, v1);
        d2.operate(a2, v2);
    }

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

10 20 30 40

Expected Output

Bus ready Driver started Driver started Bus write: 10 20 Bus write: 30 40 Driver stopped Driver stopped Bus stopped