2014-06-10 209 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; 

} 

}