【发布时间】:2021-10-11 06:24:49
【问题描述】:
我正在尝试就如何处理多个输入和多个输出提出一个低级设计。具体来说,关于 Amazon Alexa。
Alexa 可以接受多个输入 -> 语音/文本。 Alexa 可以输出多个输出 -> 语音/文本/电子邮件等。
你会使用什么设计模式?
【问题讨论】:
标签: oop design-patterns
我正在尝试就如何处理多个输入和多个输出提出一个低级设计。具体来说,关于 Amazon Alexa。
Alexa 可以接受多个输入 -> 语音/文本。 Alexa 可以输出多个输出 -> 语音/文本/电子邮件等。
你会使用什么设计模式?
【问题讨论】:
标签: oop design-patterns
我会将消息转换和消息处理划分为单独的组件,因为它们是两个不同的问题。通过转换,您可以使用多态性,因此可以轻松添加新格式。所以它会是这样的:
class Alexa {
fun process(input: AlexaInput): AlexaOutput
}
class AlexaInput(
//.. whatever raw data Alexa input consists of (regardless of the format it came as)
)
class AlexaOutput(
//.. whatever raw data Alexa output consists of (regardless of the format it came as)
)
interface AlexaInputConverter<T> {
fun convert(input: T): AlexaInput
fun supports(inputMessageType: InputMessageType): Boolean
}
interface AlexaOutputConverter<T> {
fun convert(output: AlexaOutput): T
fun supports(outputMessateType: OutputMessageType): Boolean
}
class AlexaVoiceInputConverter: AlexaInputConverter<VoiceMessage> {
override fun convert(input: VoiceMessage): AlexaInput {
// ... implementation of voice to AlexaInput
}
override fun supports(inputMessageType: InputMessageType): Boolean {
return inputMessageType == VOICE;
}
}
class AlexaTextInputConverter: AlexaInputConverter<TextMessage> {
override fun convert(output: AlexaOutput): TextMessage {
// ... implementation of output to text
}
override fun supports(inputMessageType: InputMessageType): Boolean {
return inputMessageType == TEXT;
}
}
class AlexaVoiceOutputConverter: AlexaOutputConverter<VoiceMessage> {
override fun convert(output: AlexaOutput): VoiceMessage {
// ... implementation of raw data to Voice Message
}
override fun supports(outputMessateType: OutputMessateType): Boolean {
return outputMessateType == VOICE;
}
}
class AlexaTextOutputConverter: AlexaOutputConverter<TextMessage> {
override fun convert(output: AlexaOutput): TextMessate {
// ... implementation of raw data to Text Message
}
override fun supports(outputMessateType: OutputMessateType): Boolean {
return outputMessateType == TEXT;
}
}
fun main() {
val inputConverters = getInputConverters()
val outputConverters = getOutputConverters()
val inputMessage = getInputMessage()
val inputData = inputConverters.first { it.supports(inputMessage.type) }.convert(inputMessage)
val outputData = alexa.process(inputData)
val outputFormat = getPreferredOutputFormat()
val outputMessage = outputConverters.first { it.supports == outputFormat }.convert(outputData)
// do something with the output message...
}
我在这里使用 Kotlin 作为首选语言,但您可以在大多数语言中实现类似的模式。 除了可扩展性之外,这种结构很容易编写单元测试。
【讨论】: