本文介绍了这是什么设计模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了关于的维基百科文章和,但以下代码似乎并不适合任何地方。有人可以向我解释以下模式是什么还是反模式?

I read the Wikipedia articles on FactoryMethod and AbstractFactory but the following code doesn't seem to fit anywhere. Can someone explain to me what the following pattern is or if it is an anti-pattern?

interace PaymentGateway{
  void makePayment();
}

class PaypalPaymentGateway implements PaymentGateway
{
  public void makePayment()
  {
    //some implementation
  }
}


class AuthorizeNetPaymentGateway implements PaymentGateway
{
  public void makePayment()
  {
    //some implementation
  }
}

class PaymentGatewayFactory{
  PaymentGateway createPaymentGateway(int gatewayId)
  {
    if(gatewayId == 1)
      return PaypalPaymentGateway();
    else if(gatewayId == 2)
      return AuthorizeNetPaymentGateway();
  }
}

假设用户使用收音机选择付款方式按钮在html页面上,gatewayId是从单选按钮值派生的。

Let's say the user selects the payment method using a radio button on an html page and the gatewayId is derived from the radio button value.

我看过这样的代码,以为是AbstractFactory模式,但是在阅读维基百科文章之后我有疑问。

I have seen code like this and thought it was the AbstractFactory pattern but after reading the Wikipedia article, I'm having doubts.

推荐答案

网关类实现,选择委托给我称之为参数化工厂。

the gateway class implements a strategy pattern with selection delegated to what I'd call a parameterized factory.

如果你想将它减少到一个GOF模式,我会说它更像是一个,缩写成一个简写调用,而不是设置策略并调用build()。

If you want to reduce it to one of the GOF patterns I'd say it is more like a builder pattern, condensed into a shorthand call instead of setting the strategy and calling build() afterward.

如果您想扩展到Fowler模式,您可以将其与

If you want to extend to Fowler patterns, you can compare it to a Registry

这篇关于这是什么设计模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:15