The trouble with using a factory for game objects

In Chapter 5, Decoupling Code via the Factory Method Pattern we learned how to use a Dynamic Factory to decouple our stages, components, and objects from higher level modules. We did this by placing the dependencies of each derived class into a separate builder class instead of a high-level module. Let's look at an example of creating a derived type stage builder:

//SplashStageBuilder.h-------------------- 
#include "M5StageBuilder.h"

class SplashStageBuilder: public M5StageBuilder
{
public:
virtual M5Stage* Build(void);
};

//SplashStageBuilder.cpp--------------------
#include "SplashStageBuilder.h"
#include "SplashStage.h"

M5Stage* SplashStageBuilder::Build(void)
{
return new SplashStage();
}

The reason we did this is so that changes to the SplashStage class only affect this file as opposed to the M5StageManager, for example. This means any changes to derived stage or stage builder classes cannot break other code, because the other code will only be using an M5Stage pointer. Changes to this class could still break other code, particularly if this stage was removed from the game altogether. However, by minimizing dependencies, we reduce the chances that other code will need to be changed in the future.

In the Mach5 Engine, the M5Stage derived classes only need a default constructor. This is by design to keep the builder classes as simple as possible. Each stage class will read its own required data from a file. The logic for which file to read is written into the constructor. The same simple default constructor design is used in the M5Component derived classes as well. What this means is that instead of needing to create a builder class for each stage or component, we can instead use the power of C++ templates:

//M5StageBuilder.h 
class M5StageBuilder
{
public:
virtual ~M5StageBuilder(void) {} //empty virtual destructor
virtual M5Stage* Build(void) = 0;
};

template <typename T>
class M5StageTBuilder: public M5StageBuilder
{
public:
virtual M5Stage* Build(void);
};

template <typename T>
M5Stage* M5StageTBuilder<T>::Build(void)
{
return new T();
}

By using C++ templates, we can reduce the number of small classes that need to be manually created while still gaining the decoupling benefits of the factory. Of course, it is always possible that a few stages or components will need more complex constructors or builder classes. In that case, we can easily create the required classes when the need arises. Unfortunately, we don't get the option of using templates with our object types.

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

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