0

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

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

代码如下所示:

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

现在我的问题是:

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

然后它看起来像这样:

4

1 回答 1

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());

享受编码!

于 2019-06-21T08:02:31.177 回答