Search code examples
javaswingobserver-pattern

Solutions to implement Observer pattern to my application


I want to implement the Observer pattern to my application.Since my code is large i will sum the problem. So, i have to make a application that manages the relations between a boss and some employees. For this, I have two separate gui for both the boss and employee.

When i lunch the application i create two loggins , one for boss and one for employee. If the loggin for boss is succesfull then it will create a new Gui Boss frame

If the employee loggin is successfull then a new Gui Employee will show up. What i want to do, is to add for the new Gui Employee created (wich is observable) an observer (Gui Boss). Here is some of my code to explain better:

//in Application.java
public static void main(String args[]){
    ........
    LoginBoss lb = new LoginBoss(contrb);  //contrb is boss controller
    lb.setVisible(true);
    LoginEmployee le = new LoginEmployee(contre); //contre is employee controller
    le.setVisible(true);
}

//In LogginBoss.java
//after i check if it's ok i create a new gui boss
guiB = new GuiBoss(contrb,boss);  //contrb is boss controller passed from loggin boss
guiB.setVisible(true);

//In LogginEmployee.java
///after i check if it's ok i create a new gui employee
guiE = new GuiEmployee(contre,employee);
guiE.setVisible(true);
//now i whant to add for guiE an Gui Boss observer, something like guiE.addObserver(guiB);

If you have any ideeas please, let me know.I'm sorry for my english.


Solution

  • Take a look at this link.

    If GuiEmployee extends the Observer pattern, you should make something like:

    GuiEmployee watched = new GuiEmployee(var, var);
    
    watched.addObserver(guiB);
    
    watched.changeSomeValue(value);
    

    In the changeSomeValue method,inside GuiEmployee (watched in my example) you must include these sentences to notify observers:

    setChanged();
    notifyObservers(value);
    

    A call to notifyObservers will do nothing until setChanged is called. For more info, take a look here.