WindowListener for closing JFrames and use global variable

我的梦境 提交于 2019-12-02 07:42:26

In the past when I faced the same issue, I decided to implement a Singleton pattern to keep the user's current session "global". This way I have access to the current session in any class I need.

It should be something like this:

public class SessionManager {

    private static SessionManager instance;
    private Session currentSession; // this object holds the session data (user, host, start time, etc)

    private SessionManager(){ ... }

    public static SessionManager getInstance(){
        if(instance == null){
            instance = new SessionManager();
        }
        return instance;
    }

    public void startNewSession(User user){
        // starts a new session for the given User
    }

    public void endCurrentSession(){
        // here notify the server that the session is being closed
    }

    public Session getCurrentSession(){
        return currentSession;
    }
}

Then I call endCurrentSession() inside windowClosing() method, like this:

public void windowClosing(WindowEvent e) {
    SessionManager.getInstance().endCurrentSession();
}

Note: calling this method here will execute in the Event Dispatch Thread causing GUI "freezes" until this method is done. If your interaction with the server takes a long time, you'd want to make this in a separate thread.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!