0

所以这里是场景。假设您有 10 个不同的供应商提供您销售的产品。现在对于这个场景,假设每个供应商都有自己的订单处理方法,并且每个都需要自己的类。这是一个很大的假设,但我试图在没有所有细节的情况下简化我的真实场景。

具有单表继承 (STI) 的解决方案

class Supplier < ActiveRecord::Base
  has_many :products
  # Methods that can be inherited by each supplier go here
end

class MySupplier1 < Supplier
  # Custom per-supplier methods go here
end

class MySupplier2 < Supplier
  # Custom per-supplier methods go here
end

这个解决方案的奇怪之处在于您的供应商表中有 10 行。例如,您永远不会拥有多个 MySupplier1 的实例。

这是另一个解决方案:

替代模块化解决方案

class Supplier < ActiveRecord::Base
  has_many :products
end

class Suppliers::Base
  # Methods that can be inherited by each supplier go here
end

class Suppliers::MySupplier1 < Suppliers::Base
  # Custom per-supplier methods go here
end

class Suppliers::MySupplier2 < Suppliers::Base
  # Custom per-supplier methods go here
end

有了这个解决方案,我喜欢它感觉更加模块化,但是 ActiveRecord 供应商和 Suppliers::MySupplier1 之间的关系真的很尴尬。基本上,我必须将供应商类存储在供应商表中,这样我就知道要实例化哪个类进行处理。

有没有人认为有对或错,甚至更好的方法?

4

0 回答 0