模板模式下泛型的簡單使用

直接放代碼。。。。

接口定義(爲限制請求和響應的參數類型,請求和響應參數設置爲泛型)

 1 public interface IFundFlowService<Req extends BaseRequest,Resp extends BaseResponse> {
 2 
 3     /**
 4      * 資金操作
 5      *
 6      * @param request 資金操作請求對象
 7      */
 8     Resp execute(Req request);
 9 
10     /**
11      * 查詢
12      * @param requestId
13      * @return
14      */
15     Resp query(String requestId);
16 
17 }
View Code

 

模板類(實現了核心方法,子類了繼承該模板類並實現抽象方法):

 1 @Service
 2 public abstract class FundFlowTemplate<Req extends BaseRequest,Resp extends BaseResponse>
 3         implements IFundFlowService<Req,Resp> {
 4     private static Logger logger = LoggerFactory.getLogger(FundFlowTemplate.class);
 5 
 6     /**
 7      * 事務模板
 8      */
 9     @Autowired
10     private TransactionTemplate txTemplate;
11 
12 
13     /**
14      * 資金流轉
15      *
16      * @param request
17      */
18     @Override
19     public Resp execute(Req request) {
20         //構建執行上下文
21         FundContext fundContext = this.buildContext(request);
22 
23         try {
24             //01、業務數據校驗
25             this.busiValid(fundContext);
26 
27             //02、請求數據落地
28             this.save(fundContext);
29 
30             //03、加載賬戶(&賬戶不存在則開戶)
31             this.loadAndOpenAcct(fundContext);
32 
33             //04、資金操作
34             this.fundOperate(fundContext);
35 
36         } catch (Exception e) {
37             //TODO 統一異常處理
38         } finally {
39             // 更新請求狀態
40             this.update(fundContext);
41         }
42 
43         //TODO 構建響應結果
44         return null;
45     }
46 
47 
48 
49     /**
50      * 更新請求狀態
51      * --業務調用方必須實現
52      *
53      * @param fundContext
54      */
55     protected abstract void update(FundContext fundContext);
56 
57 
58 }
View Code

最關鍵的請注意:實現的接口中未傳入泛型實參,模板類需要將泛型的聲明一起加入類中

 

實現類1:

 1 @Service
 2 public class FundFrozenServiceImpl extends FundFlowTemplate<ACCTFrozenReq, ACCTFrozenResp>{
 3     private final RequestTypeEnum fundType = RequestTypeEnum.FROZEN;
 4 
 5 
 6     @Override
 7     public ACCTFrozenResp query(String requestId) {
 8         return null;
 9     }
10 
11 }
View Code

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章