【问题标题】:How can I refactor this ruby code using the Open/Closed principle or Strategy pattern如何使用 Open/Closed 原则或策略模式重构此 ruby​​ 代码
【发布时间】:2018-07-24 05:58:34
【问题描述】:

如何使用开放/封闭原则或策略模式重构此 ruby​​ 代码? 我知道主要思想是“软件实体(类、模块、函数等)应该对扩展开放,但对修改关闭”但是我如何在实践中使用它呢?

class PaymentService
  def initialize(payment, payment_type)
    @payment = payment
    @payment_type = payment_type
  end

  def process
    result = case payment_type
    when 'first'
      process_first
    when 'second'
      process_second
    end

    payment.save(result)
  end

  def process_first
    'process_first'
  end

  def process_second
    'process_second'
  end
end

【问题讨论】:

  • “但因修改而关闭”——不在 ruby​​ 中。无法阻止任何一段代码被 ruby​​ 中的第 3 方修改。
  • 我想你的意思是result = case @payment_type in PaymentService#process

标签: ruby-on-rails ruby strategy-pattern open-closed-principle


【解决方案1】:

在此示例中,您可以构建一个带有处理付款的类的对象,而不是传递 payment_type

class FirstPayment
  def process
    'process_first'
  end
end

class SecondPayment
  def process
    'process_second'
  end
end

class PaymentService
  def initialize(payment, payment_strategy)
    @payment = payment
    @payment_strategy = payment_strategy
  end

  def process
    result = @payment_stategy.process
    payment.save(result)
  end
end

PaymentService.new(payment, FirstPayment.new)

因此,PaymentService 行为可以通过传递新策略(例如,ThirdPayment)来扩展,但如果处理第一次或第二次付款的逻辑不需要修改该类变了。

【讨论】:

    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多