如何使用“打开/关闭”原理或“策略”模式重构此ruby代码

时间:2018-07-24 05:58:35

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

如何使用“打开/关闭”原理或“策略”模式来重构红宝石代码? 我知道主要思想是“软件实体(类,模块,函数等)应该开放以进行扩展,而封闭以进行修改”,但是我如何在实践中使用它呢?

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

1 个答案:

答案 0 :(得分:4)

在此示例中,无需传递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行为,但是如果处理第一个逻辑,则无需修改该类。或更改第二笔付款。