【问题标题】:Java 7 - Stream data through class hierarchyJava 7 - 通过类层次结构流式传输数据
【发布时间】:2015-08-12 00:44:15
【问题描述】:

我正在尝试编写某种类层次结构,更具体地说,是执行层次结构。数据应该通过每个元素在层次结构中向下传递,同时在过程中进行修改。并发不是问题,尽管它是多线程程序的一部分。 澄清一下:我确实想要类的层次结构,我想要实例的层次结构。像这样的:

public abstract class ExecutionElement extends OutputStream {
    private ExecutionElement child;
    private InputStream input;

    public ExecutionElement(InputStream input) {
        this.input = input;
    }

    public ExecutionElement(ExecutionElement parent) {
        parent.addChild(this);
    }

    private void addChild(ExecutionElement child) {
        this.child = child;
    }

    protected PipedOutputStream processData() {
        // process the data according to the purpose of the current element. 
        // pseudocode from here
        // this is the root element, read from the InputStream and write to child element 
    }

    protected PipedOutputStream processData(PipedOutputStream data) {
        // this is an intermediary element, read from PipedOutputStream -->
        // convert the stream to pipedInputStream
        // process data
        // write to child
    }
}

想法如下:我将某种InputStream 传递给层次结构的根元素。然后,根元素会修改此数据(插入或删除流的特定部分),然后将其传递给子元素。冲洗并重复。

整个过程必须尽可能高效。当然,ExecutionElement 会有几种不同的实现,具有不同的目的。最近我一直在考虑使用PipedInputStreamPipedOutputStream 来加快速度,但这对我来说还行不通。此外,由于多种原因,我无法使用外部库。我们在项目中使用 Java 7,因此我们不能按照建议使用 Streams,因为这是 Java 8 的功能。

问题是:您对层次结构的设计有什么建议/建议吗?我应该遵循哪些具体的设计原则?

提前致谢。

【问题讨论】:

  • 这是家庭作业吗?也许你可以使用 Decorators.
  • @AdamArold 好吧,坦率地说是这样。但这真的重要吗?我不太明白装饰者应该如何帮助解决这个问题。你能详细说明一下吗?是的,我确实想要特定于子类的行为,但这并不能解决整体设计问题,对吗?
  • @Armand 我忘了提到,我们在项目中使用 Java 7。我会在描述中添加它。但是感谢您的提示;)
  • 您真正想要的是一个管道,在您的情况下也是 LinkedList。这与层次结构无关。

标签: java performance io stream


【解决方案1】:

您实际上想要实现Pipeline Pattern

如果您要传递字节数据,那么您已经有了一个带有 InputStream/OutputStream 类的现成实现(您可以在其中扩展 FilterInputStreamFilterOutputStream)。如果您打算传递对象,我建议您创建自己的“对象流”类(不要使用ObjectInputStream/ObjectOutputStream,它们是用于序列化的)。

【讨论】:

  • 这正是我要找的!由于我不能使用外部库,我可能会自己实现类似的东西。谢谢你指点我这个! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
  • 2021-08-07
  • 2017-04-27
相关资源
最近更新 更多