如何在其他类中使用单例模式实例。

huangapple 未分类评论46阅读模式
英文:

How do I use a Singleton instance in other classes

问题

以下是你提供的代码的中文翻译部分:

我在下面使用了单例模式来创建一个用户以便我的程序能意识到用户已登录我试图在我的 JavaFx 程序的不同页面中显示用户名因此我希望能从多个类中的实例中使用用户名详细信息当我尝试使用 `Usersession.toString`它显示非静态方法不能在静态上下文中使用的错误我该如何解决这个问题

public final class UserSession {

    private static UserSession instance;

    private String userName;

    private UserSession(String userName) {
        this.userName = userName;
    }

    public static UserSession getInstance(String userName) {
        if(instance == null) {
            instance = new UserSession(userName);
        }
        return instance;
    }

    public String getUserName() {
        return userName;
    }

    public void cleanUserSession() {
        userName = ""; // 或者 null
    }

    @Override
    public String toString() {
        return "UserSession{" +
                "userName='" + userName + "'}";
    }
}
英文:

I'm using the Singleton pattern below to create a user so that my program will be aware that a user is logged in. I'm trying to show the username in different pages of my JavaFx program so I want to use the username details from the instance in multiple classes. When I try to use Usersession.toString, it says that a non-static method cannot be used in a static context. How do I fix this?

public final class UserSession {

    private static UserSession instance;

    private String userName;


    private UserSession(String userName) {
        this.userName = userName;
    }

    public static UserSession getInstace(String userName) {
        if(instance == null) {
            instance = new UserSession(userName);
        }
        return instance;
    }

    public String getUserName() {
        return userName;
    }

    public void cleanUserSession() {
        userName = "";// or null

    }

    @Override
    public String toString() {
        return "UserSession{" +
                "userName='" + userName + "}";
    }
}

答案1

得分: 0

实际上,您试图在没有其实例的情况下访问方法。
正确的方法如下:

UserSession.getInstace("您的用户名详细信息").toString();

然后根据您的toString()方法,它将返回如下详细信息:
UserSession{userName='您的用户名详细信息'}

英文:

Actually you trying to access method without its instance .
Right way to do it as below:

UserSession.getInstace("your username details").toString();

then it will return below details as per your toString() method:
UserSession{userName='your username details}

huangapple
  • 本文由 发表于 2020年4月10日 13:44:43
  • 转载请务必保留本文链接:https://java.coder-hub.com/61134665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定