Sponsored By

The first important feature I defined for Bengine is something that manage the creation of a system (renderer, networking, physics, sounds, ...) with a generic interface. This is called an abstract factory. As Wikipedia define it:

Benoit Tremblay, Blogger

March 16, 2009

2 Min Read

The first important feature I defined for Bengine is something that manage the creation of a system (renderer, networking, physics, sounds, ...) with a generic interface. This is called an abstract factory.  As Wikipedia define it:

"A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. [...] This pattern separates the details of implementation of a set of objects from its general usage." (Wikipedia)

However, their is an important difference for mine. I don't need to be able to have more than one implementation at the same time. I want something really generic I can easly use and change.

One way I saw before is with GUID. You give the GUID of your abstract class and it returns a void pointer. Then, you can down cast it.

One way I found is little bit scary, but make no overhead and is really simple to use. I am using template specialization. The only problem I had before is I cannot use it with a dynamic library because templates are managed at compilation time. This is how I do it:

AbstractFactory.h:

class AbstractFactory
{
public:
    template
    static shared_ptr Create();
};

#define REGISTER_ABSTRACT_OBJECT(abstract, class)   \
template<>                                                                      \
shared_ptr AbstractFactory::Create()            \
{                                                                                      \
    return shared_ptr(new class());                 \
}                                                                                      \

RenderSystem.cpp:

REGISTER_ABSTRACT_OBJECT(IRenderSystem, RenderSystem);

To solve the problem that we cannot use a dynamic library, we need to put the REGISTER_ABSTRACT_OBJECT in a RenderSystemSpecializations.h and include it just one time inside your program. This is not really nice because you have to change it every time you change your implementation, but it's working.

Maybe this is too much complicated for nothing. Someone have a better way? How are you making your abstract factory? Post it in the comment section, I don't have the absolute truth.

Read more about:

Blogs
Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like