<分区>
我正在使用 php
创建一个 USSD 页面。我以前做过这个,这是一个时间紧迫的黑客工作;基本上是一个巨大的文件,其中包含手机用户可能处于的所有可能状态的 switch 语句(然后保存在数据库中并在下一个 USSD 请求时检索)——一种状态机。
这一次我有更多的时间并且想使用更专业的东西。是否有任何设计模式或最佳实践可用于此类场景?
<分区>
我正在使用 php
创建一个 USSD 页面。我以前做过这个,这是一个时间紧迫的黑客工作;基本上是一个巨大的文件,其中包含手机用户可能处于的所有可能状态的 switch 语句(然后保存在数据库中并在下一个 USSD 请求时检索)——一种状态机。
这一次我有更多的时间并且想使用更专业的东西。是否有任何设计模式或最佳实践可用于此类场景?
最佳答案
我也遇到过这个问题。我的方法是使用一棵树,其中每个 ussd 状态都是一个节点。让我用最好的方式来说明
interface Node {
render(),
process(input)
}
节点分为选择节点和输入节点。
选择节点只是向用户提供可供选择的选项,然后将用户引向其子节点或显示错误消息
class Selection extends Node {
Node[] children;
string title;
render() {
// create a ussd menu here appending title to
// menu items based on this.children
}
process(input) {
// get input and select from children node
// call its render method
}
}
输入节点收集用户的实际输入(如姓名、凭证号等)并进行处理,如查询数据库或调用远程 API,然后向用户提供响应。
class Input extends Node {
string title;
string instruction;
Handler handler;
render() {
// show title and/or instruction to user
}
process(input) {
// validate input and then pass to this.handler
}
}
为了进一步解耦逻辑,我添加了一个处理程序接口(interface),每个输入节点都需要有一个处理程序。所有的处理逻辑都驻留在Handler中
interface Handler {
handle()
}
现在,您创建了一个 Resolver 类来处理 ussd session 信息和所有 http 内容(如果您通过 http 接收 ussd 请求)。 Resolver 还根据用户输入遍历树以收集负责的 Node,然后调用它的 render 或 process 方法。你的树看起来像这样
new Selection('Main Menu (title)', [
new Selection('My account', [...]),
new Input('Recharge', 'Enter voucher number', new RechargeHandler())
]);
这是针对我的用例的有限解决方案,我相信它可以扩展以适应其他情况。我想听听其他人是如何解决这个问题的
关于php - ussd的设计模式建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7492272/