2017-04-04 26 views
0

在使用枚舉類型時是否存在某種避免很多if語句的方法?也許我應該使用一些設計模式,而不是使用if語句。如何在使用枚舉類型時避免if語句等於?

我在我的代碼,很多情況下,它看起來像這樣://僞代碼

public void methodOne() {  
    if(User.Type.SomeType == user.Type && User.Type.SecondType == user.Type) 
     doSomething(); 
} 

public void methodTwo() { 
    if(!User.Type.OtherType == user.Type && !User.Type.SecondType == user.Type) 
     throw new BadTypeException(); 
    doSomething(); 
} 
+1

'if(User.Type.SomeType == user.Type && User.Type.SecondType == user.Type)'永遠不會匹配正確嗎?你是不是指'||'? – john16384

+1

你可以發佈你的實際用例嗎?如果語句通常可以用枚舉中定義的方法,多態方法以及諸如「訪問者」之類的設計模式來替換 - 但是您必須考慮具體情況以瞭解採用哪種方法 – Joni

回答

5

使用EnumSet

​​
+0

是的,這看起來好多了if(!User.Type.OtherType == user.Type &&!User.Type.SecondType == user.Type)。謝謝:) –

+0

這應該是'私人靜態最終設置 SET'。請注意,*變量*可能是最終的,但EnumSet本身仍然是可變的;使用'SET = Collections.unmodifiableSet(EnumSet.of(...))'使它真正成爲不可變的。 – VGR

+0

我用正確的類型更新了答案。我遺漏了不可改變的部分,這對於'私人'並不是真正的問題(一個班級應該知道如何處理自己的領域)。 – john16384

1

我個人喜歡用可變參數的函數這種情況下,特別

private static boolean matchesAnyState(User.Type type, User.Type... types) { 
    for (User.Type listType: types) { 
     if (type.equals(listType)) { 
      return true; 
     } 
    } 
    return false; 
} 
0

當然,您可以創建一個實用程序類並將這些檢查移動到靜態滿足hod,但這不是面向對象的方式,不會修復你的設計。

相反,我會建議你考慮子類化你的用戶。 因此而不是User.Type,你將不得不interface Userabstract class User和亞型:

class AdminUser implements User 

class GuestUser implements User 

等。 方法doSomething應該移到您的User接口並由子類實現。 你只需要你的用戶doSomething