I have a application and i need to user Observer to resolve. Since the code implementation is long i would like to sum the problem.
I start the application.
I have a LogInWindow where i can choose Secretary or Student.
The secretary can add students, courses and results for a student at a given course.
The student can only see its results.
I need to use Observer so that if a Secretary is Logged in an instance of that application and a Student is logged in another instance of that application, when the Secretary adds a result for that student at a course, that student sees instantly on its list that new course and its result.
The data is read from txt files.
My solution.
SecretaryWindow is an Observer
StudentWindow is an Observer
ResultRepositoryFile is the Observable object
When i click AddButton the controller Adds a Result(studentName, courseName, result) to the ResultRepositoryFile. The SecretaryWindow observer sees that, prints a message and saves the txt file containing the ResultRepositoryFile.
Now in StudentWindow i click a RefreshButton and the ResultRepositoryFile is reloaded in the list from this window, showing the newly added Result.class
Is this the right way to do it, because i have doubts.
How to sync the two instances of the same application using Observer ?
Thanks for reading and hope you can help me.
If you’re going to have more than one person using your application at the same time, you should use a database, rather than text files. Text files can get corrupted if more than one person writes to them at the same time.
I suggest a relational database like MySQL.
Since your student window has a refresh button, your student window will always pull the most recent data from the database.
When the secretary adds a result to the database, the database will lock, and not allow anyone to access that one and only result until after the add is committed to the database. The database allows access to other results at the same time the secretary is adding a result.
You do not need an Observed and Observable, unless you want to signal a student that a secretary has added a result to the database.
Edited to add:
The secretary window is the Observed, and the Observable is the result that the secretary has added to the text file.
The student window updates the window based on the Observable. The secretary window has to be able to access the student window instance based on the student id of the result.