Should a Finder Method be part of the Data Mapper, or part of the domain class?

In Martin Fowler's Patterns for Enterprise Application Architectures book (page 229 in German, Lazy Load) he gives an example with this code:

public List getProducts() {
    if (products == null) products = Product.findForSupplier(getID());
    return products;
}

like you can see, the finder method seems to be part of the domain class Product. This confuses me a little bit, since I thought everything related to retrieving objects from somewhere (often a database, but business logic shouldn't care) should be part of the Data Mapper (PersonDataMapper) class. Probably I just missed something?


The example you gave is the easy method for Lazy Loading. Person is unlikely using a DataMapper. As Fowler states in the english book (201):

Using lazy initialization is simple, but it does tend to force a dependency between the object and the database. For that reason it works best for ActiveRecord, Table Data Gateway and Row Data Gateway. If you are using Data Mapper, you'll need an additional layer of indirection, which you can obtain by using a virtual proxy [GOF].

As for everything [...] should be in the DataMapper, well.. yes, but also no. What you should keep in mind when working with design patterns is when to use them and when not. DataMapper is not the Holy Grail. It's not the only way to do it. When your app is just a small and simple CRUD app living on the web, then the added complexity of a Data Mapper and/or using a Domain Model is likely not worth the effort.

In addition, design patterns are generic good practise approaches to common software problems. While you may be able to apply them to your concrete problems as they are given in a book, there is no reason to follow them religiously. If something in a pattern would overly complicate your problem solving, then keep it simple. Derive. Adjust. Solve the problem.

链接地址: http://www.djcxy.com/p/56284.html

上一篇: Data Mapper可以调用另一个? 并继承?

下一篇: Finder方法应该是数据映射器的一部分还是域类的一部分?