【问题标题】:Improving my code with loose coupling or high coupling if any?如果有的话,用松耦合或高耦合改进我的代码?
【发布时间】:2019-11-03 08:21:06
【问题描述】:

我想通过创建与我的代码的更低耦合度来使用 GRASP 改进我的代码。在我的示例中,我不确定我是否在进行低耦合,以及我是否在进行松耦合而不是高耦合?

我正在使用 Spring Boot 制作我的项目。在我的管理控制器中,我正在处理两个类:RestaurantcardServiceContentsectionService(来自我的服务层)。这两个类都实现了名为I_RestaurantcardServiceI_ContentsectionService 的接口。

代码如下所示:

public class AdminController {
RestaurantCardService restaurantcardService;
ContentsectionService contentsectionService;
public AdminController (){
    this.restaurantcardService       = new RestaurantCardService ();
    this.contentsectionService       = new ContentsectionService ();
}

现在我的问题是:

如果我实现RestaurantCardServiceContentsectionService 的接口作为属性的数据类型而不是类本身,耦合不会下降,因为我们可以在RestaurantCardService 的另一个变体中实现接口和ContentsectionService?

然后它看起来像这样:

【问题讨论】:

  • 你在说什么耦合?包之间或一个包中的类之间的耦合?一般来说,应该对同一个包中的类进行强/高耦合,而对不在同一个包中的类进行非常低的耦合。包结构的设计对于维护来说真的很重要。
  • 也许软件工程 Stackexchange 更适合这类设计原则问题
  • 我试图改进格式,但似乎有些代码最后缺少您提出的想法。

标签: java loose-coupling coupling grasp


【解决方案1】:

这是高度耦合的代码。您已经在类本身中硬编码了您的依赖项。这将使类难以进行单元测试。

好的方法应该是通过构造函数获取依赖,并且每个服务都应该有接口。

例如:-

 public class AdminController {
            private final RestaurantCardService restaurantcardService;
            private final ContentsectionService contentsectionService;
            public AdminController (final RestaurantCardService rcs,final ContentsectionService  css){
                this.restaurantcardService       = rcs;
                this.contentsectionService       = css;
            }

 AdminController  ac = new AdminController (new RestaurantCardServiceImpl(),new ContentsectionServiceImpl());


            so for unit testing you can pass mock services;

            for intance:


    AdminController  ac = new AdminController (new MockRestaurantCardServiceImpl(), new MockContentsectionServiceImpl());

享受编码!

【讨论】:

    猜你喜欢
    • 2022-07-06
    • 2017-05-09
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多