3

我是一个相对较新的 C++ 程序员。
在编写一些代码时,我创建了一些与下面的代码在概念上相似的东西。当一位朋友指出这实际上是一种工厂模式时,我阅读了有关该模式的信息并看到它与此相似。

在所有示例中,我发现工厂模式总是使用单独的类来实现,class BaseFactory{...};而不是像我使用静态create()成员函数实现的那样。

我的问题是:
(1)这实际上是工厂模式吗?
(2) 代码似乎有效。我实现它的方式有什么不正确的吗?(3) 如果我的实现是正确的,那么与单独的类相比
,实现静态函数的优缺点是什么。create()BaseFactory

谢谢!

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();
}
4

2 回答 2

3

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.

于 2013-10-01T20:26:31.853 回答
1

你的工厂没问题,只是你合并了工厂和接口,违反了SRP原则。

不要在基类中创建静态方法,而是在另一个(工厂)类中创建它。

于 2013-10-01T20:21:54.247 回答