سؤال

I am a relatively new C++ programmer.
In writing some code I've created something similar in concept to the code below. When a friend pointed out this is in fact a factory pattern I read about the pattern and saw it is in similar.

In all of the examples I've found the factory pattern is always implemented using a separate class such as class BaseFactory{...}; and not as I've implemented it using a static create() member function.

My questions are:
(1) Is this in fact a factory pattern?
(2) The code seems to work. Is there something incorrect in the way I've implemented it?
(3) If my implementation is correct, what are the pros/cons of implementing the static create() function as opposed to the separate BaseFactory class.

Thanks!

class Base {
    ...
    virtual ~Base() {}
    static Base* create(bool type);
}

class Derived0 : public Base {
    ...
};

class Derived1 : public Base {
    ...
};

Base* Base::create(bool type) {
    if(type == 0) {
        return new Derived0();
    }
    else {
        return new Derived1();
    }
}

void foo(bool type) {
    Base* pBase = Base::create(type);
    pBase->doSomething();
}
هل كانت مفيدة؟

المحلول

This is not a typical way to implement the factory pattern, the main reason being that the factory class isn't typically a base of the classes it creates. A common guideline for when to use inheritance is "Make sure public inheritance models "is-a"". In your case this means that objects of type Derived0 or Derived1 should also be of type Base, and the derived classes should represent a more specialised concept than the Base.

However, the factory pattern pretty much always involves inheritance as the factory will return a pointer to a base type (yous does this too). This means the client code doesn't need to know what type of object the factory created, only that it matches the base class's interface.

With regard to having a static create functions, it depends on the situation. One advantage, as your example shows, is that you won't need to create an instance of the factory in order to use it.

نصائح أخرى

Your factory is ok, except for the fact that you merged the factory and the interface, breaking the SRP principle.

Instead of making the create static method in the base class, create it in another (factory) class.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top