当一个类只调用另一个具有多个方法的类的一个方法时,如何减少耦合?
我有一个类(我们称之为 MyService
),它在其构造函数中接受两个依赖项。第一个与问题不太相关。第二个是PaymentDetails
。 PaymentDetails 的生命周期比 MyService 长,MyService 是由工厂创建来处理此特定请求的。
在 MyService.process()
中,它:
- 使用第一个依赖项执行一些操作,
- 构造一个
new TransactionDetails()
对象并在其上设置各种内容, - 调用
myPaymentDetails .setTransactionDetails( td );
- 返回一些内容,说明向导中接下来的页面
PaymentDetails
必然包含许多方法。它是一个实体样式对象,当用户逐步浏览一系列大约 5 个页面时,信息就会构建到其中。
令我困扰的是,正如所写,我的服务类依赖于整个 PaymentDetails ,但只调用一个方法。
这让我很困扰,因为:
- 它将限制重用服务类的能力,
- 无法通过阅读方法签名来了解真正的依赖项是什么
我的问题是:
解决此问题的最佳方法是什么,以便我的服务类具有最小的依赖性?
I have a class (let's call it MyService
) that accepts two dependencies in it's constructor. The first one is not all that relevant to the question. The second one is PaymentDetails
. PaymentDetails lives for longer than the MyService, which is created by a factory to process this particular request.
In MyService.process()
, it:
- does some stuff with the first dependency,
- constructs a
new TransactionDetails()
object and sets various things on it, - calls
myPaymentDetails.setTransactionDetails( td );
- returns something to say which page in the wizard follows next
PaymentDetails
has by necessity many methods on it. It is an Entity style object into which information is built up as the user steps through a series of about 5 pages.
What is bothering me is that as written my service class depends on the whole of PaymentDetails
but only calls one single method.
This bothers me because:
- it will limit the ability to re-use the service class
- it is not possible to understand what the real dependencies are by reading the method signatures
My question is:
What is the best way to fix this so that my service class has minimal dependencies?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个简单的接口:
让
PaymentDetails
声明它实现该接口:当然它已经实现了所需的方法。那么
MyService
只需要处理TransactionAcceptor
接口,而不需要与PaymentDetails
耦合。You could create a simple interface:
Have
PaymentDetails
declare that it implement the interface:And of course it already implements the required method. Then
MyService
only needs to deal with theTransactionAcceptor
interface and not be coupled withPaymentDetails
.添加一个
接口 Transactionable
或其他东西,并让 PaymentDetails 实现它。在 MyService 中仅处理“Transactionables”。
Add an
interface Transactionable
or something and let PaymentDetails implement it.In MyService deal with 'Transactionables' only.