Game Development Reference
In-Depth Information
Listing 23-1. A Factory for Creating
Option
Instances
Option* CreateOption(PlayerOptions optionType)
{
Option* pOption = nullptr;
switch (optionType)
{
case PlayerOptions::GoNorth:
pOption = new MoveOption(
Room::JoiningDirections::North,
PlayerOptions::GoNorth, "Go North");
break;
case PlayerOptions::GoEast:
pOption = new MoveOption(
Room::JoiningDirections::East,
PlayerOptions::GoEast, "Go East");
break;
case PlayerOptions::GoSouth:
pOption = new MoveOption(
Room::JoiningDirections::South,
PlayerOptions::GoSouth,
"Go South");
break;
case PlayerOptions::GoWest:
pOption = new MoveOption(
Room::JoiningDirections::West,
PlayerOptions::GoWest,
"Go West");
break;
case PlayerOptions::OpenChest:
pOption = new OpenChestOption("Open Chest");
break;
case PlayerOptions::AttackEnemy:
pOption = new AttackEnemyOption();
break;
case PlayerOptions::Quit:
pOption = new QuitOption("Quit");
break;
case PlayerOptions::None:
break;
default:
break;
}
return pOption;
}
As you can see, the
CreateOption
factory function takes a
PlayerOption enum
as a parameter and
then returns an appropriately constructed
Option
. This relies on polymorphism to return a base
pointer for the object. The knock-on effect of this use of polymorphism is that any factory function