The Static Factory

The simplest way to implement a factory method the way we want is with either a global function or a static class function. We could define a function called MakeStage outside of StateMananger that is responsible for instantiating the correct derived type based on a parameter. In this case, we will use an enum called StageType to help us choose our correct type:

//MakeStage.cpp 
Stage* MakeStage(StageType type)
{
switch(type)
{
case ST_Level1:
return new Level1;
case ST_LEVEL2:
return new Level2;
case ST_MainMenu:
return new MainMenu;
default:
//Throw exception or assert
}
}

If we use this style of factory, our StageManager::Update function will look like this:

void StageManager::Update() 
{
Stage* pStage = MakeStage(currentStage);

pStage->Init();

while(currentStage == nextStage)
pStage->Update();

pStage->Shutdown();
DestroyStage(pStage);//Clean up the stage when done
}

This version of the factory method works exactly as we want. We can now choose which derived Stage class is instantiated. We still have a switch statement that we must maintain, but at least our higher-level module is no longer dependent on derived classes. In the default case, where our switch statement can't match the correct type, we are left with the choice of using an assert to crash the program, throwing an exception and letting the client resolve the issue, or perhaps returning null, which still gives responsibility to the client.

The Static Factory successfully decouples our StageManager class from specific derived Stage classes, while allowing us to choose which stage will be instantiated at runtime. This is great, but as I said, this isn't how the Mach5 Engine implements Stage or component factories. Instead, Mach5 uses a more dynamic solution, so we will call it the Dynamic Factory.

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

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