gpt4 book ai didi

c++ - 这是哪个设计模式 : Factory Method or Abstract Factory

转载 作者:太空狗 更新时间:2023-10-29 20:59:46 27 4
gpt4 key购买 nike

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

我在下面发布了一个代码片段。是否有人可以告诉我这是哪一个以及(如果可能)可以对代码进行哪些更改以使其归入其他类别?

#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);
}

最佳答案

这不是 GOF 创建模式。它是抽象工厂模式的变体,有时也称为参数化工厂模式。参数化工厂根据传递给创建方法的参数(通常是 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 {
// ...
}
};

关于c++ - 这是哪个设计模式 : Factory Method or Abstract Factory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23864033/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com