簡體   English   中英

在使用相似對象的多個服務中重用相似方法的最佳方法是什么?

[英]What is the best approach to reuse similar method in multiple Services that use similar objects?

我有幾個服務具有由調度程序調用的相同方法。 這是一項服務的一個例子。

@Service
public class MyService1 {

     @Autowired
     private MyLocalMapper1 localMapper1;
     
     @Autowired
     private MyLocalRepository1 localRepository1;

     @Autowired
     private MyExternalMapper1 externalMapper1;
     
     @Autowired
     private MyExternalRepository1 externalRepository1;
  

     public void startProcess() {
          //I use the mappers and the repositories in here
     }
}

我有 15 個服務與這個服務完全相似,但每個服務都有一個特定的映射器(例如 MyLocalMapper2、MyLocalMapper3 等)以及存儲庫。

例如

 @Service
 public class MyService2 {

     @Autowired
     private MyLocalMapper2 localMapper2;
     
     @Autowired
     private MyLocalRepository2 localRepository2;

     @Autowired
     private MyExternalMapper2 externalMapper2;
     
     @Autowired
     private MyExternalRepository2 externalRepository2;
  

     public void startProcess() {
          //I use the mappers and the repositories in here
     }
}

考慮到它使用的對象在每個服務中都不同,是否有任何設計模式允許重用 startProcess 方法中的代碼?

我想為每個 object 創建接口,例如:LocalMapperInterface、LocalRepositoryInterface 等。並將所有這些接口作為參數傳遞給單個方法,但不確定這是否是最佳方法。

提前致謝。

我不確定,也許“模板方法模式”是一種可行的方法。

您可以創建一個抽象 class 如下所示,並在所有 15 個服務中擴展它,前提是映射器和存儲庫具有共同的父 class,您可以在抽象 class 中使用它:

    public abstract class ScheduledService {
      public void startProcess() {
        LocalMapper localMapper = getLocalMapper();
        LocalRepository localRepo = getLocalRepository();
        ExternalMapper externalMapper = getExternalMapper();
        ExternalRepository externalRepo = getExternalRepository();
        // use above objects here!!
      }

      public LocalMapper getLocalMapper();

      public LocalRepository getLocalRepository();

      public ExternalMapper getExternalMapper();

      public ExternalRepository getExternalRepository();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM