0

GRASP を使用して、コードとの結合をさらに低くすることにより、コードを改善したいと考えています。私の例では、低結合を作成しているかどうか、高結合ではなく疎結合を作成しているかどうかわかりません。

Spring Boot を使用してプロジェクトを作成しています。私の admincontroller では、2 つのクラスを処理しています: RestaurantcardServiceand ContentsectionService(私のサービス層から)。これらのクラスは両方とも、I_RestaurantcardServiceおよび と呼ばれるインターフェースを実装していますI_ContentsectionService

コードは次のようになります。

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

今私の質問は:

クラス自体ではなく、属性のデータ型としてRestaurantCardServiceとのインターフェイスを実装すると、との別のバリエーションでインターフェイスを実装できるため、結合が低下しませんか?ContentsectionServiceRestaurantCardServiceContentsectionService

次に、次のようになります。

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 に答える