The Factory method pattern
The Factory method pattern is exactly the design pattern we need to solve our problem. The purpose of this pattern is to have a way of creating the derived class that we want without needed to specify the concreate
class in our high-level module. This is done by defining an interface for creating objects, but letting subclasses decide which class to instantiate.
In our case, we will create a StageFactory
interface with a method called Build
that will return a Stage*
. We can then create subclasses such as Level2Factory
to instantiate our derived classes. Our StageManager
class now only needs to know about the Stage
and StageFactory
abstractions:
Creating a Stage Factory
//StageManager.cpp void StageManager::Update() { Stage* pStage = m_stageFactory->Build(); pStage->Init(); while(currentStage == nextStage) pStage->Update(); pStage->Shutdown(); m_StageFactory->Destroy(pStage);//stage must be destroyed }
Notice that we have moved the call...