解析文本的设计模式

时间:2016-08-27 19:52:44

标签: parsing design-patterns

我有一个逻辑问题。我必须编写一个程序来解析不同类型的消息。 下面我展示了这些消息的示例:

MESS1

DATE=06.06.2016
CAR_MODEL=OPEL

#Total_Number3
#Max_HP123


MESS2

DATE=12.01.2016
CAR_MODEL=FORD

MARTIN/SMITH
JOHN/PUTIN


MESS3

DATE=13.12.2016
CAR_MODEL=BMW

1/3/4

我知道以简单的方式编写代码并不困难,但我想使用设计模式实现这一点,这样我就可以轻松修改它 出现新类型的消息,某种类型的消息更改或消息包含不同顺序的数据。

P.S我在思考Builder,但是消息不包含相同的字段,所以在我看来它不合适。

提前问候和感谢!

2 个答案:

答案 0 :(得分:2)

根据你的问题,我假设你有几个MessageFormats,它们有一些共同的字段和有些不是,需要一种机制来解析每一个。

Visitor模式是您绝对需要的。

您可以按如下方式组织课程。所以这里的访客是不同的MessageFormats。它们可以从一个共同的父母继承,因为它们有一些共同的属性,而MessageParser是照顾每个访客的照顾者。

public abstract class MessageFormat{
    private String commonField1;
    private String commonField2;

    //getters and setters.
}

public class MessageFormat1 extends MessageFormat{
    private String nonCommonField1;
    private String nonCommonField2;

    //getters and setters.
}

如上所述,您可以定义不同的消息格式MessageFormat2,MessageFormat3等。现在您应该使用method overloading来实现看护者类(MessageParser)的方法来完成访问者模式。

public class MessageParser{

    public void parse(MessageFormat1 mf){
        //logic specific to MessageFormat1.
    }

    public void parse(MessageFormat2 mf){
        //logic specific to MessageFormat2.
    }

}

如果你想有一些解析公共字段的常用逻辑,你可以在MessageParser类中做类似的事情。

public class MessageParser{

    public void parse(MessageFormat1 mf){
         parse(mf); //calling private method.
        //logic specific to MessageFormat1.
    }

    private void parse(MessageFormat mf){
        //logic common to all MessageFormats.
    }

}

请注意,我提到的退货类型应根据您的要求进行调整。

答案 1 :(得分:0)

public class CarMessageModel
{
public string Name {get; set}
}

public class AnimalMessageModel
{
public string Name {get;set;}
public int Age {get;set;]
}


public interface IMessageVisitor
{
 void Visit(AnimalMessageModel model);
 void Visit(CarMessageModel model);
}

public class NameVisitor : IMessageVisitor
{
 void Visit(AnimalMessageModel model)
{
  model.Name = "Some animal Name";
}
 void Visit(CarMessageModel model)
{
  model.Name = "Some Car Name";
}

}

public class AgeVisitor : IMessageVisitor
{
 void Visit(AnimalMessageModel model)
{
  model.Age = 4;
}
 void Visit(CarMessageModel model)
{
  throw new NotImplementedException(); <-- Becase no needed Model, does not contain Age Property
}

}

你可能会说我应该创建包含通用逻辑而不是每个逻辑方法的属性的访问者类,但是遵循这个想法我也可以在不使用访问者模式的情况下创建代码。

提前致谢。