我的最佳方式之間徘徊,以實現此服務:依賴注入的正確實施
目前我有這樣的:
class ReissueInvoices
def initialize(registration, invoice_gateway, invoice_generator)
@registration = registration
@invoice_gateway = invoice_gateway
@invoice_generator = invoice_generator
end
def call
void_current_invoices
regenerate_invoices
create_third_party_invoices
end
private
attr_reader :registration, :invoice_gateway, :invoice_generator
def void_current_invoices
registration.invoices.each do |invoice|
unless invoice.paid?
invoice_gateway.void_invoice(invoice)
end
end
end
def regenerate_invoices
invoice_generator.call(registration)
end
def create_third_party_invoices
invoice_gateway.create_invoices(registration)
end
end
,我把這個(通常是從我的控制器)是這樣的:
ReissueInvoices.new(@registration, InvoiceGateway.new, InvoiceGenerator.new).call
我明顯有一個InvoiceGateway,InvoiceRegistration類,並將它們作爲依賴項傳遞給我的ReissueInvoices類。
這是做事情的最佳方式嗎?這是否正確實施了依賴注入?或者我應該改變我的ReissueInvoices類像這樣的初始化方法去除參數和添加私有方法來創建和訪問invoice_generator和invoice_gateway對象:
class ReissueInvoices
def initialize(registration)
@registration = registration
end
def call
void_current_invoices
regenerate_invoices
create_third_party_invoices
end
private
attr_reader :registration
def invoice_gateway
@invoice_gateway ||= InvoiceGateway.new
end
def invoice_generator
@invoice_generator ||= InvoiceGenerator.new
end
.....
,並調用它像這樣
ReissueInvoices.new(@registration).call
最後,你們怎麼想的初始化定義這樣的默認參數的:
def initialize(registration, invoice_gateway=InvoiceGateway.new, invoice_generator=InvoiceGenerator.new)
@registration = registration
@invoice_gateway = invoice_gateway
@invoice_generator = invoice_generator
end
是好是壞?
感謝,
馬特