C++ 的 抽象工厂
等级 5486 次按键
工厂函数 createShape 根据字符串选择要创建的 Shape 子类,并以 unique_ptr<Shape> 返回。调用方只使用基类接口,draw() 执行的是 Circle 的版本。
C++ 代码
// 所有图形的抽象基类1class Shape {2public: // 每种图形都必须实现 draw3 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 // 工厂:调用方无需知道具体类即可得到 Shape17unique_ptr<Shape> createShape(const string& type) { // “circle”时创建 Circle;unique_ptr<Circle> 会转换为 unique_ptr<Shape>18 if (type == "circle") return make_unique<Circle>(); // 其他字符串则创建 Square19 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