2014-06-10 207 views
4

是否有設計模式或其他方式根據類型創建類?根據類型標識創建類

我的服務器收到一個json消息,其中包含要執行的操作。

我有幾個Action類,應該映射到相應的類。

{ TYPE: 'MOVE' ... } => class ActionMove 
{ TYPE: 'KILL' ... } => class ActionKill 

(所有Action類都實現Action接口)。

如何根據類型創建類?

回答

4

如果你需要保持你的動作情況中(即原木)的跟蹤,請使用Factory Pattern

public class ActionFactory{ 
    public Action createAction(String type){ 
     if (type.equals("MOVE")) 
      return new ActionMove(); 
     if (type.equals("KILL")) 
      return new ActionKill(); 
     ... // so on for the other types 

     return null; //if the type doesn't have any of the expected values 
    } 
    ... 
} 
+0

那就是我在找的東西。但不是createAction方法不應該是靜態的嗎? – user3319474

+0

是的,您可以將其設置爲靜態,但在某些情況下,您可能還想創建一個「ActionFactory」實例。 –

+0

我很抱歉爲我的新手知識,但你可以舉個例子,爲什麼我想擁有ActionFactory的實例,如果它只是用來創建對象? – user3319474

2

創建一個HashMap映射字符串Action對象:

Map<String,Action> map = new HashMap<String,Action>(); 

map.put("MOVE", new ActionMove()); 
map.put("KILL", new ActionKill()); 

然後拿到首選值:

Action a = map.get(type); 
a.perform(); 

或任何你需要的。


如果你正在尋找靜態方法的類,你可以做反射,但你做錯了。你可能想修改你的代碼來使用對象而不是類。

+0

我目前並沒有解釋自己。我的意思是對象 – user3319474

0

好吧......

感謝您的幫助,我創建了一個工廠方法,該方法根據類型返回一個對象。

public class ActionFactory { 
public static Action createAction(JSONObject object){ 

    try{ 
     String username = object.getString("USERNAME");   
     String type = object.getString("TYPE"); 
     String src= object.getString("SRC"); 
     String dest = object.getString("DEST"); 

     if(type == "MOVE"){ 
      return new ActionMove(username,src,dest); 
     } 
     else if(type == "KILL"){ 
      return new ActionKill(username,src,dest); 
     } 

     else if(type == "DIED"){ 
      return new ActionDied(username, src, dest); 
     } 
     else if(type == "TIE"){ 
      // TODO: implement 
     } 
    } 
    catch(JSONException e){ 
     e.printStackTrace(); 
    } 


    return null; 

} 

}