getInstance() 方法如何工作以及为什么不使用 new 关键字?

How the getInstance() method works and why the new keyword is not used?

提问人:David 提问时间:8/30/2023 最后编辑:Roman CDavid 更新时间:8/30/2023 访问量:54

问:

我注意到在创建对实例的引用时没有使用关键字。下面是代码片段:new

public class SingletonExample {
    private static SingletonExample instance;

    private SingletonExample() {
        // Private constructor
        System.out.println("SingletonExample instance created.");
    }

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

    public void displayMessage() {
        System.out.println("Hello from SingletonExample!");
    }

    public static void main(String[] args) {
        // This won't work : SingletonExample instance = new SingletonExample();

        // Getting an instance of SingletonExample using getInstance() method
       SingletonExample singleton = SingletonExample.getInstance();
        singleton.displayMessage();
        
    }
}

我预计创建一个类的新实例将涉及使用关键字,但似乎该方法在没有它的情况下处理这个问题。我正在寻找解释为什么在这种情况下省略关键字以及如何使用该方法实际创建实例。newgetInstance()newgetInstance()

有人可以深入了解该方法在这种情况下的工作原理以及为什么不使用关键字?getInstance()new

Java 设计模式 单例 实例 实例化

评论

9赞 Jesper 8/30/2023
再看一遍方法。它确实用于创建一个新的.getInstance()newSingletonExample
1赞 Jon Skeet 8/30/2023
此外,实际上可以在您给出的代码中工作,因为您的方法在类中......理想情况下,您的示例将在不同的类中显示它。new SingletonExample()mainSingletonExample

答:

2赞 Roman C 8/30/2023 #1

getInstance()实际上返回先前创建并保存到变量的实例,即带有运算符的类的实例。new

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

实例化类

new 运算符通过为新对象分配内存并返回对该内存的引用来实例化类。new 运算符还调用对象构造函数。

注意:短语“实例化类”与“创建对象”的含义相同。当你创建一个对象时,你正在创建一个类的“实例”,因此“实例化”了一个类。 new 运算符需要一个 postfix 参数:对构造函数的调用。构造函数的名称提供要实例化的类的名称。

new 运算符返回对它所创建对象的引用。此引用通常分配给适当类型的变量,例如:

点 originOne = new Point(23, 94); 新运算符返回的引用不必分配给变量。它也可以直接在表达式中使用。例如:

int height = 新 Rectangle().height; 此声明将在下一节中讨论。

评论

0赞 Roman C 9/6/2023
如果这个答案对你有帮助,那么你应该把它标记为接受。我在答案左边的复选框。此外,值得投票支持帮助您的答案,以帮助其他人选择正确的答案。