strategy-pattern - 接受策略的访问者模式 - 有什么收获吗?
问题描述
我一直在我的应用程序中使用访客模式作为支付系统。我有 10 种付款方式(paypal、banktransfer、stripe、omise 等)。但是一旦我做到了,我就想知道何时可以使用策略模式的访客模式。让我向您展示我到目前为止创建的内容:
class PaymentGetCreditCardsVisitor(var presenter: MyPresenter, var usersAddress: AddressModel) : IVisitor {
override fun visit(strategy: PaymentStrategy) { //notice how its accepting a strategy !!!!!
strategy.fetchCreditCards(presenter, addressModel) //gets the cards for this payment type
}
}
interface IVisitor {
//list out all the classes the visitor can visit now
fun visit(strategy: PaymentStrategy)
}
interface IVisitable {
fun accept(v: IVisitor)
}
在代码中,我有一个工厂,可以根据用户国家/地区让我恢复付款策略:
class PaymentStrategyFactory constructor(private var payByOmiseStrategy: PayByOmiseStrategyStrategy,
private var payByBankTransferPaymentStrategy: PayByBankTransferPaymentStrategy, etc, etc,etc,etc) {
fun getPaymentStrategy(country: String): PaymentStrategy {
return when (country) {
"china" -> payByOmiseStrategy
"somalia" -> payByBankTransferPaymentStrategy.get()
}
}
}
上面发生的所有事情都是它的一个工厂,它根据我预先确定的某种类型返回支付策略。因此,如果国家是中国,我会使用 omise,如果是某个小岛,我会使用银行转账等。
以下是一种策略的外观:
interface PaymentStrategy {
fun fetchCreditCards(presenter: MyPresenter,address: AddressModel);
}
and its implementation:
class PayByOmiseInternetBankingPaymentStrategy : PaymentStrategy {
fun fetchCreditCards(presenter: MyPresenter,address: AddressModel){
//do some work and get thte credit cards for the omise card strategy
}
}
现在让我们谈谈我的担忧。以下是我实际调用访客进行工作的方式:
PaymentStrategy strategy = (PaymentStrategy) mPaymentStrategyFactory.getPaymentStrategy("china");
new PaymentGetCreditCardsVisitor(presenter, address).visit(strategy);
and the work gets done.
but could i not have also called it like this:
`strategy.fetchCreditCards(presenter, addressModel)` and not used a visitor at all ?
What are the benefits to using a visitor pattern then when i can do the same thing with a strategy ? should i be combining them like this ? is it more scalable ? the language is in kotlin but im more concerned about the implementation details of the patterns and its usage. IM concerned that my visitor is taking in a strategy to invoke ? is this not a wrapper ontop of another wrapper ? i want to know the benefits of it.
解决方案
推荐阅读
- excel - 如果尚未在工作表中,则将粘贴复制到新工作表中
- node.js - 处理 csv 文件,然后通过电子邮件发送结果
- django - 包含模板中的 Django Rest Framework 表单不会接收数据
- c# - CS0118 没有任何解决方案。“变量像类型一样使用”
- vba - 范围与规格有何不同?
- git - Git:将补丁添加到现有补丁系列
- c++ - 默认赋值运算符如何与字符串指针一起使用
- javascript - 我需要我的机器人忽略具有特定角色的用户的消息
- c# - 如何使用 ClientAssertion 定义 AuthorizationCodeTokenRequest
- java - 如何防止数组中的重复?