这是哪种设计模式:工厂方法或抽象工厂

时间:2014-05-26 06:32:15

标签: c++ design-patterns factory-pattern

我正在阅读关于创作设计模式的文章,并且设法让自己在工厂,抽象工厂和工厂方法之间完全混淆。

我在下面发布了一个代码段。有人会非常友好地告诉我这是哪一个,并且(如果可能的话)可以对代码进行哪些更改以使其属于其他类别?

#include "iostream.h"

#define QUIT 2

class Shape {
public:
    virtual void draw() = 0;
};

class Circle : public Shape {
public:
    void draw() {
        cout << "circle : draw" << endl;
    }
};
class Square : public Shape {
public:
    void draw() {
        cout << "square : draw" << endl;
    }
};

class Factory {
public:
    virtual Shape* createInstance(int id) = 0;
};

class SimpleShapeFactory : public Factory {
public:
    Shape* createInstance( int id) {
        if(id == 0)
            return new Circle;
        else if(id == 1)
            return new Square;
        else 
            return new Circle; //as a default
    }
};

int main() {
    Factory* factory = new SimpleShapeFactory();
    int choice = 0;
    Shape* shape;

    do
    {
        cout<<"\n 0. Circle";
        cout<<"\n 1. Square";
        cout<<"\n 2. Quit";
        cout<<"\n Enter your choice : ";

        cin>>choice;

        if(choice == QUIT)
            break;

        shape = factory->createInstance(choice);
        shape->draw();
    } while (choice !=QUIT);
}

2 个答案:

答案 0 :(得分:2)

有两种相关模式:Factory method patternAbstract factory pattern。你的关闭到第二个。 模式名为 Abstract

Here是他们之间的区别。

答案 1 :(得分:2)

这不是GOF的创作模式。它是抽象工厂模式的变体,有时称为参数化工厂模式。参数化工厂根据传递给create方法的参数(通常是Id或类型说明符)创建不同的对象。

你的例子中的GOF工厂方法就是这样的(只是一个例子......无意义......)

struct AreaCalculator {
    virtual double calculateArea() = 0;
};

struct CircleCalculator {
    CircleCalculator(const Circle& circle);
    double calculateArea() override;
};

struct Shape {
    virtual void draw() = 0;

    // This is the factory method:
    virtual std::unique_ptr<AreaCalculator> createCalculator() = 0;
};

struct Circle : Shape {
    void draw() override {
        cout << "circle : draw" << endl;
    }

    std::unique_ptr<AreaCalculator> createCalculator() {
        return make_unique<AreaCalculator>(*this);
    }
};

GOF抽象工厂看起来像这样

struct Circle {
    virtual void draw() = 0;
};

struct StdoutCircle : Circle {
    void draw() override {
        cout << "circle : draw" << endl;
    }
};

struct Win32Circle : Circle {
    void draw() override {
        // ....
    }
};


struct ShapeFactory {
    virtual std::unique_ptr<Circle> createCircle() = 0;
    virtual std::unique_ptr<Rect> createRect() = 0;
};

struct StdoutShapeFactory : ShapeFactory {
    std::unique_ptr<Circle> createCircle() override {
        return make_unique<StdoutCircle>();
    }

    std::unique_ptr<Rect> createRect() override {
        // ...
    }
};