Game Development Reference
In-Depth Information
The
Notify
template method specifies a method pointer parameter. The method pointer must have a
void return type and take no arguments. The type of a method pointer takes the following format.
void (Class::*VariableName)()
Class
here represents the name of the class the method belongs to and
VariableName
is the name
we use to reference the method pointer in our code. You can see this in action in the
Notify
method
when we call the method using the
Method
identifier. The object we are calling the method on here is
an
Observer*
and the address of the method is dereferenced using the pointer operator.
Once our
Notifier
class is complete, we can use it to create
Notifier
objects. Listing 23-9 inherits
a
Notifier
into the
QuitOption
class.
Listing 23-9. Updating
QuitOption
class QuitOption
: public Option
, public Notifier<QuitObserver>
{
public:
QuitOption(const std::string& outputText)
: Option(PlayerOptions::Quit, outputText)
{
}
virtual void Evaluate(Player& player);
};
QuitOption
now inherits from the
Notifier
class, which is passed a new class as its template
parameter. Listing 23-10 shows the
QuitObserver
class.
Listing 23-10. The
QuitObserver
Class
class QuitObserver
{
public:
virtual void OnQuit() = 0;
};
QuitObserver
is simply an interface that provides a method,
OnQuit
, to deriving classes. Listing 23-11
shows how you should update the
QuitOption::Evaluate
method to take advantage of the
Notifier
functionality.
Listing 23-11. Updating
QuitOption::Notifier
void QuitOption::Evaluate(Player& player)
{
Notify<&QuitObserver::OnQuit>();
}