如何以一种很好的方式从封闭类的公共嵌套类的实例访问封闭类变量?

时间:2013-04-22 01:08:56

标签: java class inner-classes

考虑java中的以下代码示例:

    public class Packet {

    protected int offset = 0;
    public int type;

    public Packet() {
        // This is the backward out-constructor. Every sub class must call its superior classes .new () to live!
        offset++; // For type
    }

    int[] compile(int[] outBuffer) {
        // This is the top-down compilation routine. Every sub class should call its superior compile() in a similar manner, as recursion is only possible this way!
        int dOffset = offset;
        outBuffer[--offset] = this.type;
        int[] result = outBuffer;
        offset = dOffset;
        return result;
    }

    public class Command {

        public int opCode;
        public int length;

        public Command() {
            // OpCode and length are set by sub-classes!
            type = 0x01;
            offset += 3;
            length = 0; // Init only
        }

        int[] compile(int[] outBuffer) {
            int dOffset = offset;
            offset -= 3;
            outBuffer[offset] = opCode & 0xFF;
            outBuffer[offset + 1] = (opCode >>> 8) & 0xFF;
            outBuffer[offset + 2] = length;
            int[] result = Packet.this.compile(outBuffer);
            offset = dOffset;
            return result;
        }

        public class HWCommand {
            // And so on... 8 more nesting levels in my project
        }

    }

    public Packet(int[] data) {
        // This is the forward in-constructor.
        if (data.length > 0) {
            type = data[offset++];
        }
    }

    public class Event {
        // ...
    }
}

我目前正在使用这样的结构,这种结构有大约9到10级这种嵌套来解码一个非常复杂的协议包,我对我的完全遗憾没有任何影响。到目前为止它工作得很好,目前只有我的任务才能使它适应某种架构。

有时,当通过该协议连接另一端的计算机还没有准备好接收新的命令包时,因为它仍在忙着处理最后一个,因为纯粹的处理是如此痛苦,它只会拒绝我的数据包并通过OpCode和一些相当无关的属性通知我。

正确的反应方式是等待一段随机时间并重试发送该命令。

现在,当我只有Packet.Command.HWCommand的实例时,我想要的是一种访问例如Packet.Command的OpCode变量的方法。 ...... .SubClass sp; - 所以我可以拥有一个带有操作码和命令的关联HashMap,只需抓住未通过成功消息确认的那些并重新发送它们。

我已经考虑过了:

  1. 实施getter和setter(对我来说似乎不是一个好主意)
  2. 保持对实例化SubClass的Packet.Command的引用(可以正常工作,但需要更改10k +代码行,因为那些发送例程正在大量使用)
  3. 泄漏这个$ 0参考。通过getter(例如创建一个parent()函数)
  4. 保存最后发送的数据包的原始数据,将其重新分析为该大规模协议数据结构,然后重新发送(似乎...... 有点对我来说很奇怪)
  5. 其中哪一种是最好的方法,还是有更好的方法我不知道?

0 个答案:

没有答案
相关问题