从另一个类中获取已存在的对象

Rag*_*rok 7 java class object

我是一个非常新的编程,想要知道我是否能以某种方式从我已经习惯new MyClass();在另一个类中使用它的类中获取对象,并且我不需要new MyClass();再次使用它.希望你明白这一点.

一些非常简单的例子:

class MyFirstClass
{
    Something st = new Something();
}

class Something()
{
    // some code
}

class MySecondClass
{
    // This is where I want to use the object from class Something()
    // like
    getObjectFromClass()
}
Run Code Online (Sandbox Code Playgroud)

Ana*_*oly 2

您可以使用单例模式来实现这一点

这是此类对象的启动示例。它有一个私有构造函数公共类方法 getInstance

静态方法,在其声明中具有 static 修饰符,应使用类名调用,而不需要创建该类的实例

当我们调用getInstance它时,它会检查一个对象是否已创建,并将返回已创建对象的实例,如果尚未创建,它将创建一个新对象并返回它。

public class SingletonObject {

private static int instantiationCounter = 0;    //we use this class variable to count how many times this object was instantiated

private static volatile SingletonObject instance;
private SingletonObject() { 
    instantiationCounter++;
}

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

    return instance;
}

public int getInstantiationCounter(){
    return instantiationCounter;
}
}
Run Code Online (Sandbox Code Playgroud)

要检查它是如何工作的,您可以使用以下代码:

public static void main(String[] args)  {
        SingletonObject object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

        object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

        object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

    }
Run Code Online (Sandbox Code Playgroud)

  • 请记住,仅提供链接的答案是不够的。如果链接消失(消失),则答案就会过时,并使其他人的网站变得混乱。您可以提供一个自给自足的答案,并附上来源链接。 (2认同)