【发布时间】:2017-09-29 20:59:53
【问题描述】:
我正在编写一个应用程序,需要我将信息写入 TFT 显示器(有点像 gameboy 显示器)。 我将信息逐行输出到显示器。我现在这样做的方式要求我为每个不同的屏幕提供一个功能。 喜欢:
void displayWelcomeMessage();
void displayInsertCoinMessage();
void displayGoodByeMessage();
每个函数都遵循这个逻辑:
void displaWelcomeMessage()
{
writeline(0, "Hi David");
writeline(1, "Welcome");
writeline(2, "Back!");
}
问题:我讨厌每个屏幕都有不同的功能。它根本不可扩展,想象一下如果我有 500 个不同的屏幕。 如何抽象写入显示的过程?这样我就得到了一个负责写入显示器的通用函数。
谢谢
更新
按照“Useless”和 Michael.P 的建议,我最终可能会做的是将每条消息的格式存储在一个文件中:
DisplayMessages.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 而不是纯文本,则可以进行进一步的改进。这样你就可以迭代每条消息的子成员(行)并相应地处理
【问题讨论】:
-
在任何情况下,您都会在许多函数(方法)或许多类中编写代码,但您可以定义一个名为
Displayer的接口(纯虚拟类),其中包含一个方法示例:display然后你在许多类中实现它,例如:WelcomeMessageDisplayer,'InsertCoinMessageDisplayer' ...然后你把所有的对象都当作Displayer。 -
问题是,目前,我有 50 种不同的显示信息(50 种不同的功能)。这意味着我将有 50 个不同的课程。必须有更好的方法来做到这一点
-
您可以将这些消息存储在一个文件中吗?然后,您可以将它们放入向量中,并根据需要遍历它们中的任意数量
-
我喜欢这个主意。这样我就不必每条消息都有一个函数(或每条消息一个类)。我更新了我的帖子
-
请注意,您仍然有一些交错的数据和逻辑(
getMessageStructureFromCfg/push_back行)。您的目标可能是只使用fetchAndDisplay("WELCOME_MESSAGE")为您自动执行该循环。
标签: c++ architecture abstraction reusability