跳转至

练习:使用抽象接口输出不同格式


任务描述

设计抽象接口 Printer,由 TextPrinterJsonPrinter 输出同一条消息的不同格式。

相关知识

抽象类可定义接口规范,让调用方依赖抽象接口而非具体实现。

依赖抽象而非实现

printMessage 的形参类型为 const Printer&,因此它不需要知道实际是文本打印器还是 JSON 打印器。新增打印格式时无需修改这个函数。

输出格式

文本格式使用全角冒号;JSON 格式中的双引号需在 C++ 字符串字面量中正确转义。

编程要求

  1. Printer 声明纯虚函数 print(const std::string&) const
  2. 文本打印器输出 文本:hello;JSON 打印器输出 {"message":"hello"}
  3. 编写 printMessage(const Printer&, const std::string&) 并用两种派生类测试。
  4. Printer 应有虚析构函数;所有 print 函数均声明为 const
  5. printMessage 不得使用 dynamic_cast 或根据具体打印器类型编写分支。

待完成代码

#include <cassert>
#include <iostream>
#include <sstream>
#include <string>

// TODO:定义 Printer、TextPrinter、JsonPrinter
void test() {
    TextPrinter text;
    JsonPrinter json;
    std::ostringstream output;
    std::streambuf* oldBuffer = std::cout.rdbuf(output.rdbuf());
    printMessage(text, "hello");
    printMessage(json, "hello");
    std::cout.rdbuf(oldBuffer);
    assert(output.str() == "文本:hello\n{\"message\":\"hello\"}\n");
}

int main() {
    test();
    std::cout << "本关测试通过" << std::endl;
    return 0;
}

测试说明

同一调用接口应支持不同输出策略。测试应通过同一个 printMessage 函数断言两行完整输出,而不是直接调用派生类的 print


开始你的任务吧,祝你成功!