C++ 的 抽象工厂

等级 5486 次按键

工厂函数 createShape 根据字符串选择要创建的 Shape 子类,并以 unique_ptr<Shape> 返回。调用方只使用基类接口,draw() 执行的是 Circle 的版本。

C++ 代码

// 所有图形的抽象基类
1class Shape {
2public:
// 每种图形都必须实现 draw
3 virtual void draw() const = 0;
// 虚析构函数;unique_ptr<Shape> 通过基类类型删除对象,因此需要
4 virtual ~Shape() = default;
5};
6
7class Circle : public Shape {
8public:
// Circle 对 draw 的实现
9 void draw() const override { cout << "Drawing Circle" << endl; }
10};
11
12class Square : public Shape {
13public:
// Square 对 draw 的实现
14 void draw() const override { cout << "Drawing Square" << endl; }
15};
16
// 工厂:调用方无需知道具体类即可得到 Shape
17unique_ptr<Shape> createShape(const string& type) {
// “circle”时创建 Circle;unique_ptr<Circle> 会转换为 unique_ptr<Shape>
18 if (type == "circle") return make_unique<Circle>();
// 其他字符串则创建 Square
19 return make_unique<Square>();
20}
21
// auto 被推导为 unique_ptr<Shape>
22auto shape = createShape("circle");
// 虚调用:输出“Drawing Circle”
23shape->draw();

运行结果

Drawing Circle
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • ;× 11
  • <× 11
  • (× 10
  • )× 10
  • "× 8
  • {× 6
  • }× 6
  • :× 5
  • =× 5
  • >× 4

C++ 等级 5 的更多代码示例

← 返回 C++ 打字练习