首页 > 解决方案 > 接受策略的访问者模式 - 有什么收获吗?

问题描述

我一直在我的应用程序中使用访客模式作为支付系统。我有 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. 

标签: strategy-patternvisitor-pattern

解决方案


推荐阅读