实体类的正确设计.需要推荐 [英] Correct design for entity classes. Need recommendations

查看:29
本文介绍了实体类的正确设计.需要推荐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有实体类User:

public class User
{
  private long id;
  private String name;

  // setters and getters
}

接下来,我添加新的实体类:Comment

Next, I add new entity class: Comment

public class Comment
{
private long id;
private String comment;

// setters and getters
}

接下来,我可以添加越来越多的实体类.

Next, I can add more and more entity classes.

而且,此时我想:我可以/必须在逻辑结构中绑定/连接我的实体类吗?

And, at this moment I think: I can/must bind/connect in logical structure my entity classes or no?

我是什么意思?我试着解释:

What I mean? I try explain:

第 1 点:所有这些类:UserComment 和更多其他 - POJO.

Point 1: All this classes: User, Comment and more other - POJO.

想法 1:需要通过接口或抽象类对此类进行逻辑绑定.

Idea 1: Need logical binding for this classes via interface or abstract class.

第 2 点:我明白了,所有实体类都有相同的方法:getIdsetId().

Point 2: I see, that All entity classes has same methods: getId and setId().

想法 2:需要避免在所有类中声明此方法.

Idea 2: Need to avoid declaration this methods in all classes.

我的解决方案:

添加接口BaseEntity:

public interface BaseEntity
{
public long getId();
public void setId(long id);
}

添加所有实体类都必须实现这个接口.

Add all entity classes must implement this interface.

结果我们在逻辑上连接了所有实体类.并且我们保证每个实体类都实现了 getId()setId() 方法.

In result we logical connect all entity classes. And we guarante that each entity class implement getId() and setId() methods.

但是这个解决方案没有解决多个声明getIdsetId的问题.

But this solution doesn't resolve problem with multiple declaration getId and setId.

一个解决方案是创建通用的 BaseEntity 类:

A solution is to create general BaseEntity class:

    public class BaseEntity
    {
      private long id;
      public long getId() {return this.id};
      public void setId(long id) {this.id = id;};
    }

并且所有实体类都必须扩展 BaseEntity 类.

And all entity class must extends BaseEntity class.

嗯,听起来不错:)

但是,使用当前的实现 - 用户可以创建实例 BaseEntityClass.这有道理吗?我可以提供创建类 BaseEntity 的可能性吗?

But, with current implementation - user can create instanse BaseEntityClass. This make sense? I can give possibility to create a class BaseEntity?

或者,好的解决方案将此类标记为abstract?你怎么看?

Or maybe, good solution mark this class as abstract? What do you think?

如果您同意我之前的所有步骤:

And if you agree with all my previous steps:

我有最后一个问题:

类之间的通信必须基于接口.但我没有实体接口.将来会给我带来麻烦吗?

Communication beetween classes must based on Interfaces. But I dont have interface for entities. It is can create problems for me in future?

谢谢.

推荐答案

是的,让你的基础实体成为一个抽象类并让其他人扩展它.

Yes, make your base entity an abstract class and let other extend it.

public abstract class BaseEntity
    {
       private long id;
       public long getId() {return this.id};
       public void setId(long id) {this.id = id;};
    }

作为一般规则,应该始终针对接口而不是实现进行编程.

As a general rule, one should always program to an interface and not to an implementation.

这篇关于实体类的正确设计.需要推荐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆