如何使用 Open/Closed 原则或策略模式重构此 ruby 代码
How can I refactor this ruby code using the Open/Closed principle or Strategy pattern
如何使用 Open/Closed 原则或策略模式重构此 ruby 代码?
我知道主要思想是 'software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification' 但我如何在实践中使用它?
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
在此示例中,您可以构建一个带有 class 的对象来处理付款,而不是传递 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
)来扩展,但是 class 不需要修改,如果更改了处理第一笔或第二笔付款的逻辑。
如何使用 Open/Closed 原则或策略模式重构此 ruby 代码? 我知道主要思想是 'software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification' 但我如何在实践中使用它?
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
在此示例中,您可以构建一个带有 class 的对象来处理付款,而不是传递 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
)来扩展,但是 class 不需要修改,如果更改了处理第一笔或第二笔付款的逻辑。