对象是否应该在构造函数中设置自己的属性?

发布于 2024-11-05 01:31:26 字数 128 浏览 0 评论 0原文

我想知道一般而言,对象是否应该根据构造函数中的一个参数来设置自身。例如:如果在构造函数中指定对象 ID,那么对象本身是否应该通过从数据库获取其他数据来设置自己的变量?或者,是否应该显式创建另一个类来创建此对象,然后该类将从该对象中隐藏数据库。

I'm wondering in general terms whether an Object should set itself based on one parameter in the constructor. For example: If in the constructor you specify the objects ID, should the object itself then set its own variables by fetching the other data from the database? Or, should another class be created explicitly for creating this object, which would then hide the database from the object.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

煮茶煮酒煮时光 2024-11-12 01:31:26

以下是我的建议

  1. 使用 ObjectFactory 模式来基于 ID 进行此构造。任何开始类似于菜谱的东西,ObjectFactory 模式效果最好。

  2. 我不建议在对象的构造函数中使用对数据库的依赖。您也可以将此数据加载逻辑放入 ObjectFactory 中。

基本上,我觉得一个类的实现应该尽可能精简。

Here are my recommendations

  1. Use an ObjectFactory pattern to this construction based on an ID. Anything that starts to resemble a recipe, an ObjectFactory patterns works best.

  2. I don't suggest using a dependency on a database inside a constructor of an Object. You can put this data loading logic in the ObjectFactory as well.

Basically, I feel that the implementation of a class should be as lean as possible.

萌化 2024-11-12 01:31:26

另一个类可能应该通过从数据库读取创建对象所需的值来实例化该对象。这是更好的关注点分离。保存值的对象可能只是一个 JavaBean,即保存值的对象。我当然不会向单个对象添加数据库访问代码。

Another class should probably instantiate the Object by reading the values needed to create it from the database. This is a better separation of concerns. The Object which holds the values would probably just be a JavaBean i.e. value holding object. I certainly wouldn't add database access code to individual objects.

抹茶夏天i‖ 2024-11-12 01:31:26

取决于场景。但根据经验,您应该尝试将对数据库的访问与对象分开。就我个人而言,我可能会选择一个构建器类,它具有用于数据库访问的可注入接口,并且会返回/构建一个对象。

请注意,在很多情况下,让对象自行创建就可以了。

Depends on the scenario. But as a rule of thumb, you should try to separate access to database from the object. Personally, I would probably go with a builder class, that has an injectable interface for database access, and would return/build me an object.

Please note, there are many scenarios where it'll be fine to let the object create itself.

过潦 2024-11-12 01:31:26

如果它足够复杂,您可以考虑实现一个工厂(http://en.wikipedia.org/wiki/Factory_method_pattern)。

我相信这可能就是您在帖子中描述的有助于创作的“另一个对象”。

If it's sufficiently complex, you could look at implementing a Factory (http://en.wikipedia.org/wiki/Factory_method_pattern).

I believe that is probably what you were describing in your post with 'another object' that helps in the creation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文