类之间的Java数据文件共享 [英] Java datafile sharing between classes

查看:215
本文介绍了类之间的Java数据文件共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小程序,从一个文件(Serialized objectInputStream)读取,这是一个注册表列表,其中每个条目有一个布尔变量设置为true或false。

I'm making a small program that reads from a file (Serialized objectInputStream), which is a registry list where each entry has a boolean variable that is set to true or false.

在这个程序中,我有两个单独的JPanel类。一个是A类,可以改变这些变量的值,另一个是B类,检查这些变量是真还是假。
这两个类是在带有main-method的gui类下创建的。

In this program I have two separate JPanel-classes. One, the A-class, that can change the value of these variables, and the other, the B-class, checks if these variables are true or false. These two classes are created under a gui-class with main-method.

如果我更改A类中的变量,我如何在B类中看到新的更新值?
我试图在每个类中做一个ObjectInput-输出流。这意味着对于每个更改,类将它写入一个文件,并在更改/读取之前读回。
这是可行的,但它是最佳的吗?有更好的方法吗?

If I change the variables in the A-class, how can I see the new updated values in B-class? I tried to do a ObjectInput- output streams in each class. That means that for each change the class wrote it out to a file and read it back in before changing/ reading. This works, but is it optimal? Is there a better way to do this?

推荐答案

我认为这是观察者模型视图控制器< a> pattern。

I think this is the typical use case for the observer and the Model view controller patterns.

控制器注册一个模型及其观察者。

The controller registers a model and its observers.

它接收请求(事件)进行更改,并将它们委派给模型。当模型改变时,它通知观察者模型有一个新的状态,他们应该做一些事情来获得这些变化。

It receives requests (events) to make changes and delegates them to the model. When the model changes it notifies the observers that the model has a new state and they should do something to get those changes.

在你的情况下 Main 可以用作 Controller Observers 将是您的 Panel1 Panel2

In your case Main could be used as a Controller and the Observers would be your Panel1 and Panel2

剩下的是 Model ,你需要创建一个新类,只有阅读和写入文件。实际上,你似乎在A-Class中有这样的代码,即 Panel1

What is left is the Model for that you'll need to create a new class witch deals only with reading and writing the file. Actually you seem to have this code in A-Class i.e. Panel1. This code needs to be moved from it to the new class.

请注意,jdk已经提供了 Observer 界面和 Observable 类。

Note that the jdk already offers an Observer interface and an Observable class.

EDIT

在java中的简单示例(链接

Simple example in java (link)

这篇关于类之间的Java数据文件共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆