Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
Like this article? We recommend

Getting into a State

We now have a generic state base class. Listing 3 illustrates the use of the base class to create an initial state subclass for the program.

Listing 3 The InitialState class.

class InitialState : public State {
public:
 static InitialState* Instance();
 virtual char* whatCanWeDo(void);
 explicit InitialState();

private:
 static InitialState m_InitialState;
};

The InitialState class is a subclass of State with a few additions. The member function Instance() is used to return an instance of this class. In fact, this is the one and only instance of this class—the so-called singleton. Listing 4 illustrates the implementation of the Listing 3 interface.

Listing 4 Implementation of the InitialState class.

InitialState InitialState::m_InitialState;

InitialState::InitialState()
{
}

char* InitialState::whatCanWeDo(void)
{
 return "Capabilities: You can move to the purchase state or exit\n";
}

InitialState* InitialState::Instance()
{
 return &m_InitialState;
}

Listing 4 illustrates the Instance() method returning a pointer to a static instance of the InitialState class. The method whatCanWeDo() illustrates the capabilities of this state—you can move to the purchase state or the exit state. Next, let’s look at the PurchaseState class in Listing 5.

Listing 5 The PurchaseState class.

PurchaseState PurchaseState::m_PurchaseState;
PurchaseState::PurchaseState()
{
}

char* PurchaseState::whatCanWeDo(void)
{
 return "Capabilities: You can purchase items or move to the exit state\n";
}

PurchaseState* PurchaseState::Instance()
{
 return &m_PurchaseState;
}

The PurchaseState class is very similar to the InitialState class. Last but not least, Listing 6 illustrates the ExitState class interface.

Listing 6 The ExitState class interface.

class State;

class ExitState : public State {
public:
 static ExitState* Instance();
 virtual char* whatCanWeDo(void);
 explicit ExitState();

private:
 static ExitState m_ExitState;
};

No big surprises in Listing 6—it’s also very similar to InitialState. Listing 7 shows the implementation of the ExitState class.

Listing 7 The ExitState class implementation.

ExitState ExitState::m_ExitState;
ExitState::ExitState()
{
}

char* ExitState::whatCanWeDo(void)
{
 return "Capabilities: You can move to the purchase state or exit the program\n";
}

ExitState* ExitState::Instance()
{
 return &m_ExitState;
}

We’ve seen all of the code segments in isolation. Now let’s put them all together.

  • + Share This
  • 🔖 Save To Your Account