5

我正在设计一个类...

有些关键方法需要将对象传递给它们,或者它们需要能够“获取”对象。

所以问题是,您应该使用 getter/setter 还是直接将对象作为参数发送给方法 - 以便方法正常工作。还是应该通过构造函数设置对象,如果它们对类的正确运行非常重要?

4

4 回答 4

8

如果在没有特定对象的情况下拥有此类的实例没有意义(例如,在没有与数据库的连接的情况下构造数据访问类可能没有意义),那么它是一个“依赖关系”并且应该是一部分的构造函数。

如果您的类可以在没有它的情况下生存,或者可以使用一些默认值,那么您可以改为将其设为属性并在使用之前检查它是否已分配。

在大多数情况下,我强烈主张构造函数依赖注入。

于 2009-03-10T22:52:02.777 回答
5

问题不在于它们有多“关键”(根据定义,每种方法都需要拥有所需的数据)。一个更好的问题是它们多久改变一次。如果每次调用方法时它们都不同(或至少合理地可能)它们应该是参数。如果预计它们在对象的生命周期(或其中很大一部分)内通常是相同的,则它们应该与对象一起存储。

在后一种情况下,不要仅仅依赖于调用 setter 的用户。如果需要它们,即使它们可以通过设置器更改,也应该在构造函数中设置它们。

于 2009-03-10T22:54:23.643 回答
3

正如您所提到的,您有以下三个选项:

使用 getter/setter

As you might know, get/set will indicate a state of the object, that is accessed multiple times(generally) during the object lifetime. So if you have a scenario like 'CrucialMethod1' to 'CrucialMethodN' consuming this state then this could be used. Additionally, this will also help in exposing the state externally.

Use as parameter to constructor

Generally, a parameter to the constructor will 'dictate' the state into which the object will be initialized. So if you have a scenario where the 'CrucialMethod' may or may not be called, then this would not be most appropriate.

Use as parameter to the method

This would be useful in the scenario when the 'CrucialMethod' acts/transforms(depends) on the parameters passed. This facilitates calling the method without dependency on the state of the parameter being.

Your call!

于 2009-03-11T11:28:59.477 回答
1

如果类正确运行需要它们,则应在构造函数中要求它们或将它们设置在其中。

至于通过与否。我更喜欢当班级可以照顾自己的时候,让它完成工作并得到它需要的东西。

于 2009-03-10T22:52:58.453 回答