按照题中要求,应该补充该类的getInstance()方法,由于Singleton类是单例的,每次调用该类的getInstance()方法都将得到相同的Singleton类型实例,所以getInstance()方法的返回类型应为Singleton。预设代码中,getInstance()方法为类直接调用,所以该方法应为静态方法,那么此处得知getInstance()方法的应为:
public static Singleton getInstance() {
}
在该方法中进行判断,若instance == null即不存在实例时则新建Singleton,否则直接返回已有的instance。将此处判断逻辑写入getInstance()方法中,补全getInstance()方法。这部分参考代码如下:
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
附上完整代码:
public class Main {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}
}
class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
//write your code here......
}