创建静态 HashMap 并将其设置到 Java 中的类中——它是真正静态的吗?

发布于 2024-11-02 23:49:58 字数 287 浏览 0 评论 0原文

我正在为类编写一个逐行解释器,并且使用 Java 来完成它。它需要动态地确定作用域,这对我来说比词法作用域更难实现。 (当我开始时,我错过了这个要求。)

在我的解决方案中,我有类来建模函数;但由于绑定必须是全局的,我认为我可以创建一个类,其唯一的工作是为所有变量绑定包含一个静态 HashMap,但将每个函数类的 HashMap 设置为指向它。

我不确定这是否会按预期工作;如果我有多个函数,我可以保证它们都可以访问我的绑定 HashMap 中的数据吗?如果答案是肯定的,那么我已经有了我的解决方案。否则,回到绘图板......

I'm writing a line by line interpreter for class and I'm using Java to do it. It needs to be dynamically scoped, which has proved to be mentally harder to implement than lexical scoping for me. (I missed this requirement when I began.)

In my solution I have classes to model functions; but since binding has to be global I was thinking that I could create a class whose only job was to contain a static HashMap for all my variable bindings, but set each function class's HashMap to point to it.

What I'm not sure about is if this will work as intended; if I have multiple functions, can I guarantee that they all have access to the data in my binding HashMap? If the answer to this is yes, than I have my solution in hand. Otherwise, back to the drawing board...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

做个ˇ局外人 2024-11-09 23:49:58

我强烈建议在这种情况下不要使用静态数据结构。想象一下,如果您想在程序的单次运行中支持两个并行会话。他们会互相干扰,不是吗?如果您需要为代码库提供测试,也会发生同样的问题。

我的建议是包含对 Hashmap 的实例引用。正如罗宾建议的那样,您可以将其放入一些公共超类中,以便避免重复。但代表函数的每个对象仍然需要对 Hashmap 的引用作为配置。

这一切让我觉得您可能会受到依赖注入的想法的启发。

I would strongly suggest not to use static data structures in this case. Imagine if you wanted to support two parallel sessions in a single run of your program. They would interfere with each other, wouldn't they. The same troubles would happen if you needed to provide tests to your code base.

My suggestion is to contain an instance reference to the Hashmap. As Robin suggests you may put it into some common superclass so that duplication could be avoided. But still each object representing a function would need the reference to the Hashmap to be put as a configuration.

This all makes me think you might be inspired by the idea of Dependency Injection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文