c++ - 您如何抽象要在屏幕上显示的信息?

标签 c++ architecture abstraction reusability

我正在编写一个应用程序,需要我将信息写入 TFT 显示器(有点像 gameboy 显示器)。 我正在逐行将信息输出到显示器。我现在做这件事的方式要求我为每个不同的屏幕都有一个功能。 喜欢:

void displayWelcomeMessage();
void displayInsertCoinMessage();
void displayGoodByeMessage();

每个函数都遵循以下逻辑:

void displaWelcomeMessage()
{
  writeline(0, "Hi David");
  writeline(1, "Welcome");
  writeline(2, "Back!");
}

问题:我讨厌每个屏幕都有不同的功能。它根本不可扩展,想象一下如果我有 500 个不同的屏幕。 如何抽象写入显示器的过程?所以我最终得到了一个负责写入显示器的通用函数。

谢谢


更新

按照“Useless”和 Michael.P 的建议,我最终可能要做的是将每条消息的格式存储在一个文件中:

显示消息.cfg

WELCOME_MESSAGE_1 = "Hi %name"
WELCOME_MESSAGE_2 = "Welcome"
WELCOME_MESSAGE_3 = "back!"

在代码中我会做类似的事情:

using Message = std::vector<QString>;

void login(){

 //Do Stuff...

 QString line
 Message welcomeMessage;

 line=getMessageStructureFromCfg("WELCOME_MESSAGE_1").arg(userName); // loads "Hi %name" and replaces %name with the content of userName
 welcomeMessage.pushBack(line); // pushes the first line to welcomeMessage

 line=getMessageStructureFromCfg("WELCOME_MESSAGE_2"); // loads "Welcome"
 welcomeMessage.pushBack(line); // pushes the second line to welcomeMessage

 line=getMessageStructureFromCfg("WELCOME_MESSAGE_3"); // loads "back!"
 welcomeMessage.pushBack(line); // pushes the third line to welcomeMessage

 displayMessage(welcomeMessage);

}

void displayMessage(Message const &msg) {
 int i = 0;
 for (auto &line : msg) {
   writeline(i, line);
   i++;
 }
}

谢谢大家的帮助!

PS:如果包含消息结构的文件使用 JSON 而不是纯文本,则可以进行进一步的改进。这样你就可以迭代每条消息的子成员(行)并进行相应的处理

最佳答案

How do you abstract the information to be displayed in a screen?

与抽象任何信息的方式相同 - 将数据从代码中移出并放入数据结构中。

您的 displayXMessage() 函数对固定序列的硬编码字符串文字执行固定序列的调用。因此,通过将数据作为参数传递,以通常的方式将算法从数据中分离出来:

using Message = std::vector<std::pair<int, std::string>>;

void displayMessage(Message const &msg) {
  for (auto &line : msg) {
    writeline(line.first, line.second);
  }
}

并用适当的数据调用它:

Message welcomeMsg { {0, "Hi David"}, 
                     {1, "Welcome"},
                     {2, "Back!"}
                   };
displayMessage(welcomeMsg);

关于c++ - 您如何抽象要在屏幕上显示的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43736154/

相关文章:

c++ - 对 cblas_sgemm 的 undefined reference

java - 向应用程序添加脚本安全性

Javascript - 在哪里放置初始化数据

c++ - 您将如何完全遵循 C/C++ 中的 Stepdown 规则?

nhibernate - 如何抽象 NHibernate 以避免紧依赖和促进测试

python - pybind11 中具有动态返回类型的函数

c++ - 为什么不能通过在错误输入后设置 std::cin.clear() 来使用 std::cin?

C++ 数组和大小

join - 微服务(应用程序级连接)更多 API 调用 - 导致更多延迟?

java - 子类的抽象类和强制方法?