是否有用于容纳业务实体的容器的 name/pattern?

Is there a name/pattern for a container that holds business entities?

我发现自己经常实施 class 作为我的业务实体的美化容器。通常我只是在 class 后缀加上 "model",这是非常缺乏描述性和广泛性的。

一个例子(python):

class MyBusinessEntity:
    pass

class MyBusinessEntityModel:
    def __init__(self):
        self.entities = []

    def create_entity(self):
        self.entities.append(MyBusinessEntity())

    # Implement the rest of the CRUD operations

这个 class 将作为我的主要数据存储库,很可能会使用某种数据访问对象进行持久存储。

这种class有名字吗?我遇到了 Repository Pattern,但我不知道那是否真的是我要找的东西。

你是对的,这基本上是 Repository Pattern. 的内存中实现,通常,应用程序服务(实现你的用例的地方)会使用它检索业务对象并对其进行处理。

存储库类型

存储库的两种主要风格是集合式存储库命令式存储库。前者尝试尽可能接近地模拟内存中的集合,而后者具有基于命令的界面。主要区别在于更新:命令样式存储库具有显式 update 方法。

用法

让我们坚持使用此示例的命令样式存储库。有了这样的例子,读取用例通常是这样的(伪代码):

books = bookRepository.findByAuthor(theAuthor)
ui.show(books)

创建调用可能类似于

book = new Book(author, isbn, ...)
bookRepository.create(book)

更新调用可能类似于

book = bookRepository.getById(bookId)
book.Author = newAuthor
bookRepository.update(book)

关于您的实施的说明

您的代码示例有点奇怪的是您的存储库自行实例化业务对象。 这不是存储库的责任。

相反,应用程序服务会创建一个,并在 create 调用中将其传递给存储库。因此,存储库上的 create 通常并不意味着 "create the business object",而是 "add this object here to the data store"。在内存存储库的情况下,这仅意味着将对象添加到内部集合。