同一实体的多个表示
考虑到避免代码复制,每次开始开发新系统时,我都会遇到一个问题:
假设我们有一个系统,我有一个客户,必须在存储库中对其进行 CRUD 并将其显示为 Web 服务中的资源。
考虑与客户相关的类,我们会有(好吧,我永远不会真正使用这些名称):
- CustomerEntity,表示用于执行系统逻辑的实体;
- CustomerRepositoryEntity,表示将存储它的表行;
- CustomerXMLEntity,代表XML节点‘客户’;
看来我将拥有三个实体,并且所有客户的属性都将位于每个类中。 我想知道是否有一种方法或模式可以将这三个类合并到同一个实体中,简称为“客户”。
这样,每次我需要创建“Customer”的新表示(例如,如果我想将其表示为 Json 元素),我不需要为它创建一个新类。 我知道这是一个非常特殊的问题,但我只是想知道它是否比我现在所做的更容易(而且更好看)。
Thinking about avoiding code replication, I got a question that catches me every time I start developing a new system:
Let's say we have a system where I have a customer, have to CRUD it in a repository and show it as a resource in a webservice.
Thinking about the classes related to the customer, we would have (Okay, I will never use these names for real):
- CustomerEntity, representing the entity used for doing the system's logic;
- CustomerRepositoryEntity, representing the table row where it will be stored;
- CustomerXMLEntity, representing the XML node 'customer';
It seems that I will have three entities and all the customer's attributes will be in each class. I was wondering if isn't there a way, or a pattern to consolidate these three classes inside the same entity, called simply "Customer".
This way, every time I need to create a new representation of "Customer" (for example, If I want to represent it as a Json element), i don't need to create a new class for it. I know it's a very particular issue, but I was just wondering if it couldn't be easier (and better looking) than how I am doing now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您在不同的应用程序中使用相同的语言...
构建一个代理类和一个后端类。
后端类靠近您的数据运行,并且仅用于向您的代理提供数据。
您的代理在任何客户端上运行,并将后端端点的位置作为初始化参数。 当在代理对象上调用 get/set 时,它会处理您的验证和业务规则,然后将请求传回后端类,该后端类处理持久数据的实现细节。
您将有两层抽象:一层用于数据持久性,一层用于业务规则。
Assuming you're using the same languages in your different applications...
Build a proxy class, and a backend class.
The backend class runs close to your data, and exists only to serve up data to your proxy.
Your proxy runs on any client and takes the location of the backend endpoint as an initialization parameter. When a get/set is called on your proxy object, it handles your validation and business rules, then hands the request back to your backend class, which handles the implementation details of persisting your data.
You'd have two layers of abstraction: one for data persistence, and one for business rules.