访客模式接受策略-有收获吗?

时间:2018-08-09 12:29:02

标签: strategy-pattern visitor-pattern

我在我的应用程序中一直使用“访客”模式进行支付系统。我有10种付款方式(贝宝,银行转帐,条带,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. 

0 个答案:

没有答案