2010-06-25 81 views
0

我有一個情況(僞代碼):決策設計模式幫助

Action a; 
Object o; 
if(objectIsPartOfGroup(o, "Group1")) 
    a = treatCaseGroup1(); 
if(a != indecisive) 
    return a; 

if(objectIsPartOfGroup(o, "Group2")) 
    a = treatCaseGroup2(); 
if(a != indecisive) 
    return a; 

if(objectIsPartOfGroup(o, "Group3")) 
    a = treatCaseGroup3(); 
if(a != indecisive) 
    return a; 
. 
. 
. 

,我在想,如果有這種情況適用的模式,這樣我就不必重複「如果(a!=優柔寡斷)返回a;「檢查每一步後?我發現重複這個代碼是不是很專業?它增加了很多代碼行,完全沒有幫助清晰,因此我覺得它很糟糕。

編輯:一個對象可以是group1和group2以及group3等的一部分......所以說一個對象是group1的一部分,並且該動作是未決定的,因爲它也是group2的一部分,它將被再次處理並且再次,直到所有組都得到了治療。最後,結果也可能是不明確的!

感謝您的幫助!

戴夫

回答

3
public Action determimeAction(Object o, List<String> groups) { 
    for (String group : groups) { 
     if (((GroupI) o).isPartOf(group)) { 
      Action a = ((GroupI) o).treatCaseGroup(group); 
      if (a != indecisive) { // could this be a.isDecicive() 
       return a; 
      } 
     } 
    } 
    return null; // or whatever 
} 

public interface GroupI() { 
    public Action treatCaseGroup(String group); // is implemented to know which Action to get. 
    public Boolean isPartOf(Stirng group); // is implemented the same as your example just move the method to your object 
} 

public class GroupImpl implements GroupI { 
    public Boolean isPartOf(Stirng group) { 
    } 
    public Action treatCaseGroup(String group) { 
     // use if, case, factory, or Dep Inection to get the correct action. 
    } 
} 

不知道所有的邏輯是這樣的應該工作。

+0

謝謝,這將工作!我會等待看看是否有其他想法出現 – 2010-06-25 20:19:09

2

退房的Visitor design pattern

實質上,訪問者模式是關於在不同的靜態對象上執行不同的操作,而不會將它們綁定得太緊。

正確重構你的代碼,你會簡單地做:

o.treat(); 
+0

SRY我不是清楚。如果對象是group1的一部分,它也可以是group2,group3等的一部分,所以如果我打電話給treat();在我的對象上,它仍然可以完成「不敗」。另外,最終的結果可能是不明確的。請糾正我,如果我完全當然! – 2010-06-25 19:03:43

-2

這不是一個模式,這是沒有什麼深入的(它解決只有你問到具體的事情),但會是這樣的工作?

Action a; 
Object o; 

while (a == indecisive) 
{ 
    if(objectIsPartOfGroup(o, "Group1")) 
     a = treatCaseGroup1(); 
    if(objectIsPartOfGroup(o, "Group2")) 
     a = treatCaseGroup2(); 
    if(objectIsPartOfGroup(o, "Group3")) 
     a = treatCaseGroup3(); 
} 

return a 
+0

sry我不清楚。如果對象是group1的一部分,它也可以是group2,group3等的一部分。因此,如果我這樣做,o,即group1和2的一部分,將始終對group1進行處理,並始終處於不決定的狀態。 – 2010-06-25 19:04:40

+0

@David:根據Yuval A所說的,訪客設計模式可能是你應該去的方式。 – JAB 2010-06-25 19:18:22

+0

我只是不明白如何訪問者可以多次處理單個對象,如果它的不同組的部分 – 2010-06-25 19:43:17