当一个类只调用另一个具有多个方法的类的一个方法时,如何减少耦合?

发布于 2024-10-29 12:38:23 字数 698 浏览 1 评论 0原文

我有一个类(我们称之为 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 技术交流群。

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

发布评论

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

评论(2

小情绪 2024-11-05 12:38:23

您可以创建一个简单的接口:

public interface TransactionAcceptor {
    void setTransactionDetails(TransactionDetails td);
}

PaymentDetails 声明它实现该接口:

public class PaymentDetails implements TransactionAcceptor {
    ...
}

当然它已经实现了所需的方法。那么MyService只需要处理TransactionAcceptor接口,而不需要与PaymentDetails耦合。

You could create a simple interface:

public interface TransactionAcceptor {
    void setTransactionDetails(TransactionDetails td);
}

Have PaymentDetails declare that it implement the interface:

public class PaymentDetails implements TransactionAcceptor {
    ...
}

And of course it already implements the required method. Then MyService only needs to deal with the TransactionAcceptor interface and not be coupled with PaymentDetails.

晨曦慕雪 2024-11-05 12:38:23

添加一个接口 Transactionable 或其他东西,并让 PaymentDetails 实现它。
在 MyService 中仅处理“Transactionables”。

Add an interface Transactionable or something and let PaymentDetails implement it.
In MyService deal with 'Transactionables' only.

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