比方说,我有一个帐户类和一个AccountReport类。在帐户#显示我想显示一个帐户的报告。 Account和AccountReport都有一些公开的方法。以下哪种技术更好?委托或实例化额外的类?
1)实例化一个账户和一个账户报告,用账户数据初始化账户报告。
class AccountsController < ActionController::Base
def show
@account = current_user.account
@account_report = AccountReport.new(@account.orders)
respond_with(@account)
end
# ...
end
2)允许帐户的实例来实例化AccountReport和委托方法调用
class Account < ActiveRecord::Base
attr_reader :account_report
delegate :method_a, :method_b, :method_c, :method_d, :to => :account_report
after_initialize :setup_account_report
def setup_account_report
@account_report = AccountReport.new(orders)
end
# ...
end
选项2似乎是一个更简洁的方法给我,但有很多的方法加载了帐户使得它感觉像一个上帝阶级。
我想我明白了。我喜欢懒惰地加载报告的想法。是否有可能以这种方式委托给AccountReport/Report,或者是否需要使用方法链接account.report.total,并使用此方法? –
'@report || = AccountReport.new(self.orders)'是你上面试图做的一个很好的比喻。 –
谢谢!我已经将这两条建议结合起来,它的运作非常好。我甩掉了我的读者,写了一个获取报告的方法,然后在那里返回或初始化它。 –