Java正确解析

Java正确解析,java,parsing,design-patterns,Java,Parsing,Design Patterns,我正在寻找将手写数据解析为对象的最佳方法 假设我有一个名为IEvent的接口 假设我有两个类EventNewPlayer和EventUpdateTime,它们都实现了接口IEvent 类EventNewPlayer需要2个整数和一个字符串。让我们说出位置X和Y以及玩家的名字 类EventUpdateTime只需要一个参数:时间 我想从一个手写文件中创建尽可能多的事件 该文件如下所示: NEWPLAYER, 4, 2, joe NEWPLAYER, 8, 9, bob UPDATETIME, 1

我正在寻找将手写数据解析为对象的最佳方法

假设我有一个名为
IEvent
的接口

假设我有两个类
EventNewPlayer
EventUpdateTime
,它们都实现了接口
IEvent

EventNewPlayer
需要2个整数和一个字符串。让我们说出位置
X
Y
以及玩家的名字

EventUpdateTime
只需要一个参数:时间

我想从一个手写文件中创建尽可能多的事件

该文件如下所示:

NEWPLAYER, 4, 2, joe
NEWPLAYER, 8, 9, bob
UPDATETIME, 1
NEWPLAYER, 8, 9, carl
UPDATETIME, 3
我想从这个文件生成一个事件列表。 此外,我想在未来添加尽可能多的事件,我想

这样做的最佳/适当/可维护方式是什么

对不起,有任何英语错误,英语不是我的第一语言。

给出了

String[] data = { "ObjA,0,0,Bob", "ObjB,0" };
以及定义为

public enum MyEnum {

    ObjA, ObjB;
}
我会使用类似于:

for ( String line : data ) {

    Object obj;

    String[] parts = line.split(",");

    switch(MyEnum.valueOf(parts[0])) {

        case ObjA:
            obj = new ObjectOfTypeA(parts);
            break;

        case ObjB:
            obj = new ObjectOfTypeB(parts);
            break;
    }
然后,每个对象都可以处理自己的参数:

public ObjectOfTypeA(String[] params) {

    x = params[1];
    y = params[2];
    name = params[3];
}


对于创建的每个新对象,都需要将其添加到枚举列表、开关大小写中,然后再添加到类本身的创建中。

我建议您使用有限状态机。维护简单灵活。以后可以添加不同的处理程序

下面是我的XML解析示例-
但是您可以为文本文件解析制作类似的东西。

一种类似OOP的方法:

1) 创建一个名为
StringEventFactory
的基本接口和一个名为
parsefromary
的非静态函数,将字符串数组作为参数并返回一个
IEvent
;还创建一个名为
className
的静态函数,该函数返回每个事件类的文件名

2) 对于每个事件,创建一个相应的
…Factory
类,该类继承自
StringEventFactory
,并实现
parseFromArray
函数以从字符串数组数据创建该类型的事件

3) 创建一个哈希表,其:

  • 键是存储在文本文件中的类名,例如“NEWPLAYER”等
  • 值是对应的类
    .Factory
    对象
4) 对于每一行,将其拆分为字符串数组,并使用第一个元素从哈希表中获取
StringEventFactory
对象。将数组的其余部分传递给它的
parseFromArray
函数,以创建所需的事件对象

这样就很容易添加新的类规范,而不需要使用难看的
开关
语句


编辑:代码+规格的细微变化

 interface StringEventFactory {
    public static string className();
    public IEvent parseFromArray(string[]);
 };

 class EventNewPlayerFactory implements StringEventFactory
 {
    public static string className() { return "NEWPLAYER"; }

    public IEvent parseFromArray(string[] info) 
    {
        if (info.length != 4) // includes the class name
            return null;

        // sanity check
        if (!info[0].equals(className()) || info[3].isEmpty()) 
            return null;

        int x, y;
        try {
            x = Integer.parseInt(info[1]);
            y = Integer.parseInt(info[2]);
        }
        catch (NumberFormatException ex) {
            // notify?
            return null;
        }

        return new EventNewPlayer(x, y, info[3]);
    }
 };

 // similarly for EventUpdateTime ...

 // main body
 public static void main(string[] args)
 {
    Hashtable<string, StringEventFactory> factories = new Hashtable<string, StringEventFactory>();

    factories.put(EventNewPlayerFactory.className(), new EventNewPlayerFactory());
    // similarly for other classes

    List<IEvent> eventList = new ArrayList();

    // file parsing
    FileReader input = new FileReader(fileName);
    BufferedReader read = new BufferedReader(input);
    String line = null;

    while ((line = read.readLine()) != null)
    {    
        String[] array = line.split(",");
        for (int i = 0; i < array.length; i++)
            array[i] = array[i].trim();

        // fetch the factory class
        StringEventFactory fact = factories.get(array[0]);
        if (fact == null) {
            // class name does not exist
            continue;
        }

        StringEvent out = fact.parseFromArray(array);
        if (out == null) {
            // parameters were incorrect!
            continue;
        }

        // success! add to list
        eventList.add(out);
    }
 }
接口StringEventFactory{
公共静态字符串className();
公共IEvent parseFromArray(字符串[]);
};
类EventNewPlayerFactory实现StringEventFactory
{
公共静态字符串className(){返回“NEWPLAYER”;}
公共IEvent parseFromArray(字符串[]信息)
{
if(info.length!=4)//包含类名
返回null;
//健康检查
如果(!info[0].equals(className())| | info[3].isEmpty())
返回null;
int x,y;
试一试{
x=Integer.parseInt(信息[1]);
y=Integer.parseInt(信息[2]);
}
捕获(NumberFormatException ex){
//通知?
返回null;
}
返回新的EventNewPlayer(x,y,info[3]);
}
};
//类似地,对于EventUpdateTime。。。
//主体
公共静态void main(字符串[]args)
{
Hashtable工厂=新的Hashtable();
put(EventNewPlayerFactory.className(),neweventnewplayerfactory());
//类似地,对于其他类也是如此
List eventList=new ArrayList();
//文件解析
FileReader输入=新的FileReader(文件名);
BufferedReader read=新的BufferedReader(输入);
字符串行=null;
而((line=read.readLine())!=null)
{    
String[]数组=line.split(“,”);
for(int i=0;i

很抱歉,如果它不能直接工作并且有语法错误,我的Java有点生疏,但要点希望是你想要的。

所以不是家庭作业解决资源。请带着您的代码尝试来到这里,这些代码有一些特殊的功能problem@IvanPronin我不是要密码。我不需要写代码就知道这不是一个好方法(在“,”上拆分,条件会很容易,但很肮脏)
 interface StringEventFactory {
    public static string className();
    public IEvent parseFromArray(string[]);
 };

 class EventNewPlayerFactory implements StringEventFactory
 {
    public static string className() { return "NEWPLAYER"; }

    public IEvent parseFromArray(string[] info) 
    {
        if (info.length != 4) // includes the class name
            return null;

        // sanity check
        if (!info[0].equals(className()) || info[3].isEmpty()) 
            return null;

        int x, y;
        try {
            x = Integer.parseInt(info[1]);
            y = Integer.parseInt(info[2]);
        }
        catch (NumberFormatException ex) {
            // notify?
            return null;
        }

        return new EventNewPlayer(x, y, info[3]);
    }
 };

 // similarly for EventUpdateTime ...

 // main body
 public static void main(string[] args)
 {
    Hashtable<string, StringEventFactory> factories = new Hashtable<string, StringEventFactory>();

    factories.put(EventNewPlayerFactory.className(), new EventNewPlayerFactory());
    // similarly for other classes

    List<IEvent> eventList = new ArrayList();

    // file parsing
    FileReader input = new FileReader(fileName);
    BufferedReader read = new BufferedReader(input);
    String line = null;

    while ((line = read.readLine()) != null)
    {    
        String[] array = line.split(",");
        for (int i = 0; i < array.length; i++)
            array[i] = array[i].trim();

        // fetch the factory class
        StringEventFactory fact = factories.get(array[0]);
        if (fact == null) {
            // class name does not exist
            continue;
        }

        StringEvent out = fact.parseFromArray(array);
        if (out == null) {
            // parameters were incorrect!
            continue;
        }

        // success! add to list
        eventList.add(out);
    }
 }