gpt4 book ai didi

java - java中导入静态单例没有错误

转载 作者:行者123 更新时间:2023-12-01 08:09:18 28 4
gpt4 key购买 nike

我关注了辛格尔顿:

public class GameConfig {

private static GameConfig mGameConfig = null;

private String mStr = "Boo";

public static GameConfig getInstance(){

if(mGameConfig == null){
mGameConfig = new GameConfig();
}

return mGameConfig;
}

private GameConfig(){}

public String getStr() {
return mStr;
}
}

现在我尝试做一些实验:

假设我有其他类User来使用这个单例:

public class User{

....

private void init(){
String str = GameConfig.getInstance().getStr();
}

}

到目前为止一切顺利。

我将采用上面提到的类User并添加import static:

import static com.app.utils.GameConfig.getInstance; // no error, why?? 

public class User{

....

private void init(){
String str = GameConfig.getInstance().getStr();

// I can't type
// String str = getStr(); !!
// getInstance return instance
}
}

最佳答案

为什么没有错误呢?因为这是有效的语法。事情顺利进行不是很好吗?

import static com.app.utils.GameConfig.getInstance; // no error, why?? 

将在不命名类的情况下使 getInstance() 可用,例如:

GameConfig gc=getInstance();

顺便说一句,我会将该方法重命名为更具描述性,例如 getGameConfig

关于java - java中导入静态单例没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836553/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com