簡體   English   中英

Java如何使對象使用它實現的靜態接口方法

[英]Java How to make object use it's implemented static interface method

我有一個帶有靜態接口的類。

public class UserInfo {

   private Store userInfoStore;

   public static interface Store {
       UserInfo save(UserInfo userInfo);
   }
   public UserInfo save() {
       if (userInfoStore == null) return null;
       return userInfoStore.save(this);
   }

}

然后我有一個實現上述對象接口的對象

public class UserAuditService implements UserInfo.Store {
    @Override
    public UserInfo save(UserInfo userInfo) {
        // code that persists object to disk
    }
}

現在說我正在我的應用程序的其他地方創建UserInfo對象的實例。 如何引用UserAuditService類中實現的save方法?

UserInfo userInfo = new UserInfo();
??? - Not sure what to do here.

如果您要調用save方法,請執行以下操作:

UserInfo userInfo = new UserInfo();
UserInfo.Store userStore = new UserAuditService();
userStore.save(userInfo);

這是使用實現的方法的一種方式。

您的意思是您不想對UserAuditService類進行硬編碼,因為將來可能會有很多實現?

有許多解決方案,這就是依賴注入的全部內容。

您可以使用Spring或其他依賴注入框架,並將該類配置為在xml(或注釋)中使用。

您可以手動執行此操作,例如使用構造函數依賴項注入(將UserInfo.Store類型的字段添加到UserInfo類,並為其分配在UserInfo的構造函數中作為參數傳遞的類)。

另一個選項是setter依賴注入 - 你在UserInfo中有相同的字段,但你在創建UserInfo之后在某個地方調用的setter中設置它。

這清楚地表明了會發生什么,但是需要將依賴關系從你配置它的地方一直傳遞到它們被使用的地方,這就是人們使用依賴注入框架來削減樣板的原因。

暫無
暫無

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

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