模型,工厂和存储库

时间:2008-12-29 09:18:38

标签: design-patterns model

我将旧的基于Active-Record的API移植到新结构上以使单元测试更容易等。我们使用存储库模式进行数据访问,使用StructureMap进行依赖注入。

我现在正在努力解决一切问题。以我们的“产品”类为例,我们之前将模型,存储库和工厂部件都内置到产品对象中,例如加载,编辑和保存我们可能喜欢的产品(简化): -

Dim p As New Product
If(p.Load(1))
   p.Name = "New Name"
   p.Save()
End If

为了得到一个对象集合,我们在对象上有一个共享(静态)方法,作为一个基本工厂

Dim arrProds = Product.GetProducts()

在查看几个示例后,在我们的新结构中,我们现在有了一个IProductRepository,IProductService(它是工厂)和Product模型类。所以,像这样

Dim prodSvc = ObjectFactory.GetInstance(Of IProductService)
Dim prod = prodSvc.GetProduct(1) //Prod is an Instance of 'Product'
prod.Name = "New Name"
prodSvc.Save(prod)

但是,Product类可以加载相关数据,例如

Dim arrRelatedProds = prod.RelatedProducts

Product class中的内容如下所示

Class Product
    Function RelatedProducts() As IList(Of Product)
        // prodSvc is an instance of IProductService which is passed into the 
        // Product class in the constructor (or via Dependency Injection)
        Return Me.prodSvc.GetRelatedProducts(Me.ProductID)
    End Function
End Class

我不喜欢这样,因为它很难测试,因为我不喜欢我的'Model'类(Product)直接调用IProductService类的事实。

有没有人对建立这一切的更好方法有任何建议?

干杯

詹姆斯

修改 可能是一年中错误的时间问这个!是否有任何澄清我可以添加以使这个问题回答?

2 个答案:

答案 0 :(得分:1)

我不知道它是好还是坏,但构建它的一种方法是摆脱实体/数据传输对象Product的所有智能,并放置包括Create在内的所有内容, RetreiveRetreiveAllSaveGetRelatedProducts等等IProductService。它会使你的Product代码更简单,你不必担心哪个类做什么。

答案 1 :(得分:1)

使用存储库模式而不是活动记录时,请不要引用域对象(产品)中的存储库。这并非不可能,但是当你不这样做时,你会省去很多麻烦。您可以做的最好的事情是使用支持延迟加载的ORM。就个人而言,我使用NHibernate。使您的存储库依赖于您的域对象,但域对象独立于存储库。最好的办法是不要在域对象中注入任何东西。