准备工作:
1、代码
main.cpp
#include <iostream>
using namespace std;
// 抽象产品类
class Product {
public:
virtual void operation() = 0;
};
// 具体产品A
class ConcreteProductA : public Product {
public:
void operation() override {
cout << "ConcreteProductA operation" << endl;
}
};
// 具体产品B
class ConcreteProductB : public Product {
public:
void operation() override {
cout << "ConcreteProductB operation" << endl;
}
};
class SimpleFactory {
public:
// 根据传入的参数创建不同类型的产品对象
static Product *createProduct(int type) {
switch (type) {
case 1:
return new ConcreteProductA();
case 2:
return new ConcreteProductB();
default:
return nullptr;
}
}
};
int main()
{
// 创建产品A
Product *productA = SimpleFactory::createProduct(1);
productA->operation();
// 创建产品B
Product *productB = SimpleFactory::createProduct(2);
productB->operation();
delete productA;
delete productB;
return 0;
}
Makefile:
CC = g++
CFLAGS = -g -O0
all: main
main: main.cpp
$(CC) $(CFLAGS) -o $@ $<
clean:
rm -f main
2、安装vscode插件
Extensions for Visual Studio family of products | Visual Studio Marketplace
3、配置gdb调试环境相关信息
launch.json
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "cppdbg",
"request": "launch",
"name": "GDB",
"program": "${workspaceFolder}/simpleFactory/main",
"stopAtEntry": true,
"args": [], // 程序参数
"cwd": "${workspaceFolder}",
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
}
]
}
make编译后启动程序
结果如下