2013-05-07 52 views
1

我遇到了一個代碼,其中實用程序類具有服務客戶端的靜態引用。這裏是代碼的簡化版本客戶端靜態引用的實用程序類

public class MyHelper { 

    //assume that prime service checks if the number is prime 
    private static PrimeService client; 

    public static void setClient(PrimeService client) { 
     MyHelper.client = client; 
    } 

    public static boolean isIntegerPrime(int i) { 
     return client.isIntegerPrime(i); 
    } 
} 

對這個類的設計有什麼想法?除了意外地將客戶端設置爲null之外,我無法想象使用靜態引用遠程服務客戶端的這種實用程序類的任何缺點。我有興趣從設計的角度瞭解這個班的正確性。

回答

0

你的setMethod沒有用,因爲它沒有設置靜態變量。

public static void setClient(PrimeService client) { 
     client = client; //the assignment to this variable has no effect. } 

你需要改變這

public static void setClient(PrimeService client) { 
     MyHelper .client = client; 
    } 
+0

他說,以上,「*除了意外地將客戶端設置爲空,*」 – isaach1000 2013-05-07 07:01:57

+0

這是一個很好的習慣,使所有參數最終避免這些錯誤。 – scarfridge 2013-05-07 07:02:58

+0

更新了代碼。請注意,這是一個簡化版本,而不是實際的代碼。 – u07103 2013-05-07 07:27:34

0

好吧,如果客戶端的「isIntegerPrime」你不會看到任何NullPointerExceptions的第一個呼叫之前設置。 您可能會遇到並行訪問該客戶端的問題。因此,當同步是一個問題。 如果PrimeService也在您的控制之下,並且像這樣的用法可以,那麼它也可能是使PrimeService中的方法爲靜態的選項。

0

使用此設計可能遇到的最大問題(除了併發訪問和Juned的答案中提到的編程錯誤)是您可能無意中共享狀態。 MyHelper無法確定傳遞的客戶端引用沒有在別處使用。這可能會造成封裝問題。考慮併發訪問問題。即使您製作方法isPrime(int i)​​,某個其他線程可能會調用isIntegerPrime上的PrimeService實例傳遞給MyHelper