How it works...

The observer pattern provides the ability for an observer to be notified when an event occurs. To explain how this works, let's start with the following pure virtual base class:

class observer
{
public:
virtual void trigger() = 0;
};

As shown in the preceding, we have defined observer, which must implement a trigger() function. We can then create two different versions of this pure virtual base class as follows:

class moms_phone : public observer
{
public:
void trigger() override
{
std::cout << "mom's phone received alarm notification ";
}
};

class dads_phone : public observer
{
public:
void trigger() override
{
std::cout << "dad's phone received alarm notification ";
}
};

As shown in the preceding code, we have created two different classes, both of which subclass the observer pure virtual class, overriding the trigger function. We can then implement a class that produces an event the observer might be interested in, shown as follows:

class alarm
{
std::vector<observer *> m_observers;

public:
void trigger()
{
for (const auto &o : m_observers) {
o->trigger();
}
}

void add_phone(observer *o)
{
m_observers.push_back(o);
}
};

As shown in the preceding code, we start with std::vector, which stores any number of observers. We then provide a trigger function, which represents our event. When this function is executed, we loop through all of the observers and notify them of the event by calling their trigger() functions. Finally, we provide a function that allows an observer to subscribe to the event in question.

The following demonstrates how these classes could be used:

int main(void)
{
alarm a;
moms_phone mp;
dads_phone dp;

a.add_phone(&mp);
a.add_phone(&dp);

a.trigger();
}

The output for this is as follows:

As shown in the preceding, when the alarm class is triggered, the observers are notified of the event and process the notification as needed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset