简体   繁体   English

Java模式,用于生成和解析流中的数据

[英]Java Pattern for generating and parsing data in stream

I have certain protocol that I need to parse or generate. 我有一些需要解析或生成的协议。 The parsing takes an InputStream and produce different type of objects depending the byte stream. 解析采用InputStream并根据字节流产生不同类型的对象。 The generator takes different inputs and spit out an OutputStream that allows writing to a target stream. 生成器采用不同的输入,并吐出一个OutputStream ,以允许写入目标流。 Before reading / writing to the stream there might be some header variables that needs to be initialized. 在读/写流之前,可能需要初始化一些头变量。

For code right now looks something like follows: 现在的代码如下所示:

// Parser.
DataX parsed = DataX.parse(new ByteInputStream(new byte [] {..}));
// Access short field of DataX.
System.out.println(parsed.getX() + parsed.getY()); // data in the header.
// Access some long field by spitting InputStream.
System.out.println(parsed.buildInputStream().readFully()); // data as bytes.

// Generator.
OutputStream outstream = 
   DataX.Generator(new FileOutputStream('output')).setX(x).setY(y).build();
// Write data.
outstream.write(new byte[] {...});

DataX extends a class Data that implements two methods deserialize and serialize as abstract method which will eventually be called somewhere inside parse() and Generator() . DataX扩展了Data类,该类实现了作为抽象方法deserialize serializeserialize两个方法,这些方法最终将在parse()Generator()内部的某个地方调用。

This is a self-made design pattern, so I would like to ask if this makes sense and whether there is a more Java-ist way to do this kind of thing ? 这是一种自制的设计模式,所以我想问一下这是否有意义,以及是否有更多的Java风格的方法可以做这种事情?


Edit: The reason the stream needs to be incorporate is because the data might be huge (such as a file) and will not be feasible/desirable to store it entirely in the memory. 编辑:需要合并流的原因是因为数据可能很大(例如文件),并且无法/不希望将其完全存储在内存中。

In general it is a good idea to keep data (header values) and its presentation (streams) separate. 通常,将数据(标头值)及其表示(流)分开是一个好主意。

Some component accepts streams ( Factory method pattern) and returns plain objects. 某些组件接受流( Factory方法模式)并返回普通对象。

Those objects are serialized to streams via a different component later on. 这些对象随后将通过另一个组件序列化为流。

It shouldn't matter if it is a stream at the moment. 目前是否是流都无关紧要。 If later you want to work with Json objects - the design doesn't need to change dramatically. 如果以后要使用Json对象,则无需进行重大更改。

I think a synmetrical pattern is easy to understand. 我认为对称模式很容易理解。

// Parser
DataX header = new DataX();   // uninitialized header
InputStream is = header.input(new FileInputStream(...));
// At this point header is initialized.
// user reads data from is.

// Generator
DataX header = new DataX();   // uninitialized header
header.setX(x).setY(y);       // initialize header
OutputStream os = header.output(new FileOutputStream(...));
// At this point header is written to os.
// user writes data to os.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM