问题
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.
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.
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?

回答1:
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.
In your case Main
could be used as a Controller
and the Observers
would be your Panel1
and Panel2
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.
Note that the jdk already offers an Observer interface and an Observable class.
EDIT
Simple example in java (link)
回答2:
You could create a Class C that holds the information you read. So Class B reads the Data and puts the information to Class C. When Class A changes a value, it would fire an event to inform Class B.
You could use a HashMap<String, Boolean>
to store the data. The String is the name of the value and the Boolean is the value. Then you can make method like public void update(String name, boolean newValue)
in Class B. This method would update the Value and then invoke a method at all classes you need to inform about the new value.
回答3:
You should separate your data from the gui. Try using a Model-View-Controller design. Furthermore you could work with ActionEvents/ActionListeners in class A/B. Please provide more information on how the data is displayed.
回答4:
You can use Observer Design pattern for this situation or use case.
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
来源:https://stackoverflow.com/questions/16511210/java-datafile-sharing-between-classes