Search code examples
c++factoryabstract-factory

Is it bad practice to use an empty base class to force inheritance for an abstract factory?


I have a class called A, and say a few inherited classes based off A. I'm not including them here to save some space but also assume we have derived classes for A which would require the need for a factory. Same for class B.

struct A
{
    ...
}; 

struct B
{
    ...
};

// start of factory code
//
struct empty_base_factory
{
};

struct factoryA : public empty_base_factory
{
    shared_ptr<A> make_object() { return ... }
};

struct factoryB : public empty_base_factory
{
    shared_ptr<B> make_object() { return ... }
};

class abstract_factory
{
    std::map< uint8_t, std::shared_ptr<empty_base_factory> > iv_factories;

    public:
        abstract_factory()
        {
            iv_factories[0] = make_shared<factoryA>();
            iv_factories[1] = make_shared<factoryB>();
           // .. I might several more similar to this
        }

        std::shared_ptr<empty_base_factory> make_factory(const uint8_t i_key)
        {
             return iv_factories[i_key];
        }
};

It feels like I'm forcing an unnatural inheritance for with the empty_base_factory in order to get this implementation I found in a book to work nicely. It would make sense for make_object to be an interface method to make empty_base_factory an interface but the return type of make_object is different and I'm not sure how to handle that.

Is this a poor way of trying to implement an abstract factory by forcing the use of an empty base class? Thoughts?


Solution

  • Is this a poor way of trying to implement an abstract factory by forcing the use of an empty base class? Thoughts?

    You don't need "empty_base_factory" if it's just empty.

    In the Abstract Factory design pattern:

    The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes

    In your case: abstract_factory depends on factoryA and factoryB (which are your concrete factories) to create a concrete object. User doesn't know anything about these concrete factories' existence.

    Going back to your question: It is not really related about the Abstract Factory design pattern.

    There's no stopping you to define an abstract base class, BaseFactory, which defines what are the basic functionalities of a factory (eg. make_object()). The virtual functions in BaseFactory are what your concrete factories should implement.